Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadLocal (and Singleton) in EJB Container

I've written an authorization system which relies on objects representing the current user. To simplify programming and increase performance I want to hold those objects in a ThreadLocal after the user has logged in.

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've read that static elements make clustering problematic. If I had an UserCache on each cluster node, they all had their own cache object not synchronized with the cache objects on other nodes. Right? UserCache is a classic candidate for a singleton, because the application needs only a single instance of it. But as far as I know @Singleton EJBs have the same behaviour in a cluster.

So what to do to make UserCache clusterable in an EJB 3.1 (Java EE 6) environment?

Solutions extracted from the answers:

  • Using SessionScope from CDI (JSR 299) or
  • Using JVM clustering with Terracotta
like image 924
deamon Avatar asked Feb 03 '26 06:02

deamon


1 Answers

Since you're already on Java EE 6, wouldn't it even be a lot easier to use CDI (Contexts and Dependency Injection). This would allow to put the user info in the session scope, and inject it easily everywhere. CDI manages the rest for you.

like image 70
Chris Lercher Avatar answered Feb 04 '26 19:02

Chris Lercher