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>
deamon
source share