ThreadLocal (and Singleton) in EJB Container

不打扰是莪最后的温柔 提交于 2019-12-07 17:35:31

问题


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

回答1:


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.




回答2:


that shouldn't cause you a problem, because threads don't span different nodes anyway - or am i missing the point of your question?

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




回答3:


If you need to share objects between nodes, I would also suggest looking at the existing frameworks (like Terracotta).

Also, using ThreadLocal might possibly cause different 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 an issue here, though.



来源:https://stackoverflow.com/questions/2607019/threadlocal-and-singleton-in-ejb-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!