| Start |
|---|
| Basic ThreadLocal usage Java This can be usedwe can use The below piece of code shows how it can be used: Every thread has it’s own
Here is a small example showing use of ThreadLocal in java program and proving that every thread has it’s own copy of Output:
As we can see from the output that Thread-0 has changed the value of formatter but still thread-2 default formatter is same as the initialized value. |
ThreadLocal Java 8 functional initialization |
| Multiple threads with one shared object In this example we have only one object but it is shared between/executed on different threads. Ordinary usage of fields to save state would not be possible because the other thread would see that too (or probably not see). In Foo we count starting from zero. Instead of saving the state to a field we store our current number in the ThreadLocal object which is statically accessible. Note that the synchronization in this example is not related to the usage of ThreadLocal but rather ensures a better console output. From the output we can see that each thread counts for itself and does not use the value of the other one: RemarksBest used for objects which depend on internals during invoking a call, but are stateless otherwise, like For |
Read Article
https://develop.horje.com/learn/1434/reference