ThreadLocal for Thread-Confined Data in Java


ThreadLocal allows you to create variables that can only be read and written by the same thread, thus avoiding synchronization.

Source Code

ThreadLocal threadLocalCount = ThreadLocal.withInitial(() -> 1);
System.out.println(threadLocalCount.get()); // Outputs 1
threadLocalCount.set(2);
System.out.println(threadLocalCount.get()); // Outputs 2
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments