ThreadLocal Vs Cloning

I read about threadlocal and scripts where this is useful. I like the concept, but I wonder how it differs from cloning?

So threadlocal will return a new copy of the variable, which means that we should not use synchronization. A good example is the SimpleDateFormat object, which is not thread safe, and ThreadLocal provides a good way to use it. But why can't we just create a new clone copy to use varibale?

What adds the value provided by the ThreadLocal class compared to cloning?

+4
source share
3 answers

Using ThreadLocal, you create as many variables as there are threads, without the need for further verification. Remember, however, that the repository itself does not guarantee thread safety. You have to make sure that every object stored in local storage is used only from this stream!

If you clone objects manually, you will have to clone the object each time it is used, or check in which thread we are currently cloning.

Also, is the cloning operation thread safe? What happens if two different threads try to clone an object? Actually, I donโ€™t know, but I think that would not be the best practice.

+7
source

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.

+8
source

Using ThreadLocal is faster, a SimpleDateFormat instance stored in ThreadLocal can be reused several times in a single thread, while cloning means creating a new object each time.

0
source

All Articles