Announcement Announcement Module
No announcement yet.
[newbie] Using ThreadLocal to storing an User object. Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • [newbie] Using ThreadLocal to storing an User object.

    Hi Guys!

    I faced this code below in spring-social-quickstart example.
    Can somebody explain me why we should use ThreadLocal to store User.

    public final class SecurityContext {
    private static final ThreadLocal<User> currentUser = new ThreadLocal<User>();
    What is the real benefit to store here instead of member class variable where it is used up ?

    Thanks in advance.


  • #2
    SecurityContext is (probably) a singelton, imagine 100 hundred users setting/getting the currentuser if it was an instance variable...


    • #3
      Maybe/(im sure i dont know the benefits of ThreadLocal. So i understand the reason, but what about the how to ?
      If you have time, can you explain me how can we store 100 hundred users with ThreadLocal in a singleton SecurityContext - it sounds weird as well


      • #4
        Then I suggest a read of ThreadLocal..

        The name implies local to the thread. What it basically is (internally) it has a Map with the current thread as a key and the value is the user. So we have a single user available for the executing thread (each request has its own thread).


        • #5
          I read through the description of ThreadLocal before my previous question. But my problem was that how it takes place in servlet execution.
          I know we can create request scope classes as well what can hold request scope variables.
          But it is getting clear, we don't need any own class because Java has own (internally as you said as well) ThreadLocal to store objects for each request.