java – ThreadLocal; Is it the same every time you create a copy of a variable?
I'm still confused about the concept of ThreadLocal I've read Javadoc and other related issues, but the terminology used doesn't help me much
I know a little about ThreadLocal, that is, each thread has its own copy of variables So... How does this make it different from... Every time you build a new variable?
For example, use dateformatter as an example:
public void convertDate(String date) { // Contruct new date formatter for every invocation of the method. DateFormatter df = new SimpleDateFormatter(...); .... } public void convertDate(String date) { // Getting date formatter from threadlocal. DateFormatter df = threadLocal.get(); .... }
If all the second does is return a new copy of the variable, how is the first different from the second?
thank you.
Solution
ThreadLocal objects are usually static, which means they retain their values between function calls in the same thread
In the first code snippet, a new simpledateformatter object is created each time convertdate is called In the second fragment, each thread creates a simpledateformatter object Each time a convertDate is called in the same thread, the get () method returns the same object.
ThreadLocal objects are useful in implementing thread local storage, which means maintaining separate variable instances for each thread