ThreadLocal; Isn't it the same as creating a copy of a variable each time?

I'm still confused about the concept of ThreadLocal. I read the JavaDoc and other related questions posted here, but the jargon used and all this did not help me.

I kind of understand the idea of โ€‹โ€‹ThreadLocal, that is, each thread has its own copy of the variable. So ... how does this distinguish it from ... creating a new variable every time?

For example, using 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();
    ....
}

How is the first different from the second if everything that the second does just returns a new copy of the variable?

Thanks.

+3
source share
3 answers

ThreadLocal , , .

, convertDate, SimpleDateFormatter. SimpleDateFormatter . get() , convertDate .

ThreadLocal - , .

+10

ThreadLocal .

, , . , . (, ), .

"" , . . ThreadLocal, , . . , ( "" ) .

ThreadLocal , . InheritableThreadLocal , .

+1

, . .

, , , . ( , , , ). .

Note: local stream objects are stored on a map attached to the stream itself. If the thread dies, all objects local to this thread are GCed. Here ThreadLocal may be simpler than most caches.

+1
source

Source: https://habr.com/ru/post/1708500/


All Articles