7

I was exploring the Thread local in Java. I could not understand as why do we need this class. I can achieve the same motive if I just simply pass a new object to each thread for execution as same thing happens if i use initialValue(). I simply return a new object for each thread in initialvalue().

But say i have two threads, ThreadOne: A and ThreadTwo B. Now I want them to have a copy of own of say SimpleDateFormat class. I can do this by warping the object of SimpleDateFormat in a ThreadLocal Class and then using initialValue() I can return new SimpleDateFormat("yyyyMMdd HHmm");. Same motive I can achieve by creating two new Objects of SimpleDateFormat and p[assing one each to ThreadOne : A. and ThreadTwo : B. How does ThreadLocal help me extra

Regards,

nits.kk
  • 5,204
  • 4
  • 33
  • 55
  • 1
    Some nice answers here: http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable – JSS Jun 09 '13 at 11:02
  • 2
    +1 for question. In some 30 years of writing multithreaded apps, I have never seen a convincing argument for thread-local vars, not have I ever felt any need to use them. If I need a 'thread local' something, then it goes in as a member of the thread class - all the member functions have access to it, one 'something' per thread, job done. – Martin James Jun 10 '13 at 04:45
  • thanks for the +1 :) . But still I think I need to explore more ont he subject to get a satisfactory answer. – nits.kk Jun 10 '13 at 07:06

4 Answers4

6

There are some nice examples already here for your question.

But I try to explain the 2nd part:

But say i have two threads, ThreadOne: A and ThreadTwo B. Now I want them to have a copy of own of say SimpleDateFormat class. I can do this by warping the object of SimpleDateFormat in a ThreadLocal Class and then using initialValue() I can return new SimpleDateFormat("yyyyMMdd HHmm");. Same motive I can achieve by creating two new Objects of SimpleDateFormat and p[assing one each to ThreadOne : A. and ThreadTwo : B. How does ThreadLocal help me extra

Often, you need to format dates with a certain format, and it's ofcourse a good idea to create the SimpleDateFormat object once (instead of creating a new SimpleDateFormat for every time that you need to format a date).

So you might have something like this:

public class DateUtils {  
    private final static DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");  

    public String formatDate(Date date) {  
        return dateFormat.format(date);  
    }  
}  

This is going to fail if multiple threads call formatDate(...) at the same time (you might get strange output or exceptions) because SimpleDateFormat is not Thread-Safe. To make it thread-safe, you can use ThreadLocal:

public class DateUtils {  
    private final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {  
        @Override  
        protected DateFormat initialValue() {  
            return new SimpleDateFormat("dd-mm-yyyy");  
        }  
    };  

    public String formatDate(Date date) {  
        return dateFormat.get().format(date);  
    }  
}  

Now every thread (or call) to formatDate() method will work on a local copy and would not interfere with each other. Which gives you thread safe behavior.

Community
  • 1
  • 1
JSS
  • 2,061
  • 1
  • 20
  • 26
  • Thanks for the response. But still one thing is not clear to me.

    public String formatDate(Date date) { return new SimpleDateFormat("dd-mm-yyyy").format(date); } This would also have had the same effect. Returning new SimpleDateFormat("dd-mm-yyyy"); from initialValue() has the effect of creating new object for each thread. So how is ThreadLocal useful in this case. What is the correct use of it. ?

    – nits.kk Jun 09 '13 at 17:38
  • @nits.kk Did you find a satisfactory explanation? I still don't know what will be the difference between keeping a "private ThreadLocal" and "private static Map" in a class – rents Sep 04 '17 at 10:22
1

Thread-local storage serves the purpose of global variables within a context of a single thread.

Consider this example: you write a multithreaded program for processing user requests. Multiple users can initiate requests concurrently; your system uses one thread for each user.

When a user request arrives, your system figures out the user from which it came, and creates an instance of UserPermissions object for that user.

There are several ways to make that object available to your running program. One way is to pass UserPermissions to each method that may need it, and also to each method that calls, directly or indirectly, a method that may need it. This may be problematic, especially in contexts where callbacks are used.

Had your program not been multithreaded, you'd set UserPermissions in a global variable. Unfortunately, you cannot do that, because multiple user requests may be active at the same time.

This is where thread-local storage comes in: the process that creates the user permissions sets the UserPermissions object in thread-local storage, and leaves it there until the processing of the request is over. This way all methods can grab UserPermissions as needed, without having to pass them around as method parameters.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • What is wrong with UserPermissions as a thread class data member/field? This way all thread class methods can grab UserPermissions as needed, without having to pass them around as method parameters. – Martin James Jun 10 '13 at 04:46
  • @MartinJames A big problem with this approach is the need to subclass a thread. The need to access user info "cuts across" multiple classes, some of them may be unrelated to the thread implementation class. – Sergey Kalinichenko Jun 10 '13 at 09:38
0

You will use ThreadLocalto pass "data" to a specific thread.
For example you have a method doSomething(SomeObject a, SomeOtherObject b);
You can pass more information to this method for a specific thread of execution in a thread safe manner via thread locals than just a and b

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • Doesn't help. Loading new data into thread-locals is no more or less thread-safe than loading new data into data fields of a thread class instance, ie. not thread safe and would need synchro, in general. – Martin James Jun 10 '13 at 04:51
  • @MartinJames:No this is wrong.Threadlocal are unique and accessible to a specific thread.No synchronization needed – Cratylus Jun 10 '13 at 05:17
  • What data?Could you please provide a specific example? – Cratylus Jun 10 '13 at 19:02
0

A thread local is a cheap way to implement dynamic scoping. With dynamic scoping, a binding exists during the evaluation of a code block. In that case, the binding exists during the execution of a specific thread. Dynamic scoping was supported in early lisps, but it rarely makes sense, so most modern programming language do no support it, except via thread locals.

Dynamic scoping / thread locals are useful to maintain pervasive contextual information around, e.g.:

There's a line of research called "context-oriented programming" that aims at better supporting such concerns in programming languages. The paper "context-oriented programming: beyond layers" shows some further examples.

ewernli
  • 38,045
  • 5
  • 92
  • 123