ThreadLocal (and Singleton) in an EJB container

I wrote an authorization system that relies on objects representing the current user. To simplify programming and increase productivity, I want to save these objects in ThreadLocal after user login.

It looks like this:

public class UserCache { private static final ThreadLocal<User> cache = new ThreadLocal<User>(); public User getCurrentUser() { return cache.get(); } public void setCurrentUser(User user) { cache.set(user); } } 

I read that static elements make clustering difficult. If I had UserCache in each node cluster, they all had their own cache object, not synchronized with cache objects on other nodes. Correctly? UserCache is a classic singleton candidate because an application needs only one instance. But as far as I know, EJB @Singleton have the same behavior in a cluster.

So what to do to make UserCache grouped in EJB 3.1 (Java EE 6)?

Solutions extracted from answers:

  • Using SessionScope from CDI (JSR 299) or
  • Using JVM clustering with Terracotta li>
+3
java java-ee multithreading thread-local
source share
3 answers

Since you are already using Java EE 6, it would not be much easier to use CDI (Contexts and Dependency Injection). This will allow you to put user information in the session area and easily enter it everywhere. CDI manages the rest for you.

+5
source share

which should not cause problems because the threads do not span different nodes anyway - or am I missing the point of your question?

edit: you might want to take a look at something like terracotta - http://www.terracotta.org/ - for ways to cluster existing objects

+1
source share

If you need to exchange objects between nodes, I would also suggest looking at existing frameworks (for example, Terracotta).

In addition, using ThreadLocal can cause various problems:

http://forums.sun.com/thread.jspa?threadID=589744 http://www.devwebsphere.com/devwebsphere/2005/06/dont_use_thread.html http://www.theserverside.com/discussions/thread. tss? thread_id = 21055

This may not be a problem.

+1
source share

All Articles