If I need a ThreadLocal of a variable, is there a need to also use Supplier (also thread-safe)?
For example, isn't the Supplier unnecessary to accomplish thread-safety here?
private ThreadLocal<Supplier<MyClass>> myObject = new ThreadLocal<Supplier<MyClass>>();
Thanks.
Java ThreadLocal is used to create thread local variables. We know that all threads of an Object share it's variables, so the variable is not thread safe. We can use synchronization for thread safety but if we want to avoid synchronization, we can use ThreadLocal variables.
Most common use of thread local is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object using synchronized keyword/block. Instead, give each thread its own instance of the object to work with.
Java ThreadLocal class provides thread-local variables. It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.
Simply put, it enables you to create a generic/ThreadLocal type of object which can only be read and written (via its get and set method) by the same thread, so if two threads are trying to read and write a ThreadLocal object concurrently, one thread would not see the modification of the ThreadLocal object done by the ...
Your question doesn't show the typical way to use a Supplier with a ThreadLocal. If you want a ThreadLocal of MyClass, the old (pre-1.8) way to do that was typically:
ThreadLocal<MyClass> local = new ThreadLocal<MyClass>();
// later
if (local.get() == null) {
local.put(new MyClass());
}
MyClass myClass = local.get();
The alternative was to delcare a subclass of ThreadLocal
that overrode the initialValue
method.
In 1.8, you can instead use a Supplier to handle that initialization:
ThreadLocal<MyClass> local = ThreadLocal.withInitial(() -> new MyClass());
Functionally, these two are basically identical, but the Supplier version is a lot less code to write.
It depends on how the Supplier class is returned.
It needs to be synchronized in these cases:
It need not be synchronized in these cases:
In both cases, MyClass need not be synchronized. Because it is always local to thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With