4

In the Jersey documentation, Example 16.2 shows an example of injecting a SecurityContext into a Jersey resource singleton.

Jersey Example 16.2

Surely the docs are correct, and the example given is indeed thread safe.

I suspect that the injection of the SecurityContext happens exactly once, and when getUserPrincipal() is called, perhaps it picks up user data from some structure that is attached to the thread itself (maybe a ThreadLocal object?). That's the only way I can see that the correct user info be served to the end user when there are a ton of threads competing.

Can anyone confirm this behavior, or otherwise explain the thread safety of the Jersey example?

broc.seib
  • 21,643
  • 8
  • 63
  • 62

1 Answers1

6

Dynamic Proxies are used with a ThrealLocal backing. This is kinda explained in the JAX-RS spec, in regards to some request scoped injectable objects (See this post for spec quote)

I suspect that the injection of the SecurityContext happens exactly once

Yes this is true, but what's injected is actually a proxy. You can print out the class name and you will see that it is actually a Proxy. The first link in this post explains how it works. When you call methods on the proxy, it delegate the calls to the thread local security context.

See also:

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720