ThreadLocal does not replace synchronization or access to thread-safe objects . If the same object is assigned by ThreadLocal from different threads, then the program is no more thread safe than before: the same object will still be used for different threads.
ThreadLocal acts as a variable; that is, "names" or "refer" to the object:
[ ThreadLocal ] provides stream local variables [.. such that] each thread that accesses it (via the get or set method) has its own, independently initialized copy of the variable.
That is, what ThreadLocal does, it provides get / set isolation between threads that use the same ThreadLocal object. Thus, each thread can assign / retrieve its own different object in ThreadLocal; but to do this, you still need to โcloneโ or a new instance to start with different objects!
Remember that assignment (or method invocation) never creates an implicit clone / copy / duplicate of an object - and this extends to ThreadLocal.
user166390
source share