Question

I have been reading about threadlocal and scenarios where it is useful. I like the concept but was wondering how is it different from cloning?

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

What is the value add provided by ThreadLocal class as compared to cloning?

Was it helpful?

Solution 2

By using ThreadLocal you create as many variables as there are threads, without the need for any further checking. Remember however, that the storage itself does not guarantee thread-safety. You must make sure that each object stored in local storage is used only from that thread!

Should you clone objects manually, you would have to clone an object every time it is used, or check in which thread we are and then clone.

Besides - is cloning operation thread-safe? What would happen if two different threads attempted to clone an object? I actually do not know, but I think that it would not be good practice.

OTHER TIPS

ThreadLocal is not a replacement for synchronization or thread-safe object access. If the same object is assigned to a ThreadLocal from different threads, then the program is no more thread-safe than it was before: the same object will still be shared among the different threads.

ThreadLocal acts-like a variable; that is, it "names" or "refers to" an object:

[ThreadLocal] provides thread-local variables [.. such that] each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.

That is, what ThreadLocal does is it provides get/set isolation between threads that use the same ThreadLocal object. So each thread could assign/retrieve its own different object to the ThreadLocal; but this would still require a "clone" or new instantiation to assign the different objects to begin with!

Remember, an assignment (or method invocation) never creates an implicit clone/copy/duplicate of an object - and this extends to ThreadLocal.

Using ThreadLocal is faster, the SimpleDateFormat instance stored in a ThreadLocal can be reused multiple times in the same thread, while cloning means creating a new object every time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top