开发者

Inherent dangers of using ThreadLocal variables with EJB3?

I'm experimenting with a solution to authorization and authentication by storing a subject class in a ThreadLocal map. The design is for an API, so I won't have access to the servlets involved, and I need to use EJB3 (so CDI is not an 开发者_JAVA百科option). I have a few questions about using ThreadLocal with EJB3

  1. Presuming that each request cleans its ThreadLocal map after it's done, is there any risk in using a ThreadLocal variable with stateless session beans? In other words, is there any risk that two requests get access to the same thread at the same time?

  2. Is there any way of enforcing servlets to clean the ThreadLocal after they're done? I've looked into interceptors, but I've understood that they work poorly with EJB3, and work varyingly well in different application servers. Any other way?


Regarding Martin's answer, it's worth noting that Spring Security itself uses a ThreadLocal anyway by default (SecurityContextHolder), so I'd be cautious about using it if you need the security context to survive across EJB invocations. Certainly it won't work across remote invocations; it might with local, but I don't think there are any guarantees.

Typically, when using Spring Security I avoid EJB and use Spring Framework for wiring a POJO middle-tier and for providing services like transaction demarcation via AOP. The security context is then available throughout the middle tier as the thread remains the same across the entire call.


I'd recommend against using ThreadLocal in an EJB container. Authorisation and Authentication is a cross-cutting concern, I'd personally look at using something like AOP for that (e.g. How Spring security deals with it).


To answer my own question, no, not with any security it seems. Using a threadlocal variable may work if I have control of the whole process, but if I did then I could use CDI och JSP to keep request local variables.

Points to everybody who answered though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜