Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Use and need of thread local

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,

like image 342
nits.kk Avatar asked Jun 09 '13 10:06

nits.kk


2 Answers

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.

like image 141
JSS Avatar answered Oct 17 '22 23:10

JSS


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.

like image 44
Sergey Kalinichenko Avatar answered Oct 17 '22 23:10

Sergey Kalinichenko