Results 1 to 5 of 5

Thread: [newbie] Using ThreadLocal to storing an User object.

  1. #1
    Join Date
    Jun 2010
    Posts
    13

    Default [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.

    Code:
    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.

    Cs.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    SecurityContext is (probably) a singelton, imagine 100 hundred users setting/getting the currentuser if it was an instance variable...
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Jun 2010
    Posts
    13

    Default

    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. #4
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    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).
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  5. #5
    Join Date
    Jun 2010
    Posts
    13

    Default

    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •