Skip to main content

Java Concurrency - ThreadLocal

Greetings!

Protecting shared, mutable data is difficult. Easiest way to guarantee thread safety is not to share. This technique is called thread confinement.

One way to achieve this is using ThreadLocal class.
This uses internal thread-local variable to store data by the executing thread and provides get() and set() methods to access it.
It internally get the current thread (Thread.currentThread()) and a custom Map to assign data directly in Thread class.
This behaves like Map<Thread, T> object (though this is not how it is done).

ThreadLocal stores per-thread value and provides set(), get() methods to access it.


public class TimeHolder {

    private static ThreadLocal<Long> threadLocal = ThreadLocal.withInitial(() -> System.currentTimeMillis());
    
    public Long get() {
        return threadLocal.get();
    }
    
    public void set() {
        threadLocal.set(System.currentTimeMillis());
    }
    
    public void print() {
        System.out.println(Thread.currentThread().getName() + " : " + get());
    }
    
}


public class ThreadLocalApp {

    public static void main(String[] args) throws InterruptedException {
        TimeHolder timeHolder = new TimeHolder();
        
        timeHolder.print();
        
        Thread t1 = new Thread(() -> timeHolder.print());
        t1.start();
        t1.join();
        
        timeHolder.print();
        
        Thread t2 = new Thread(() -> {
            timeHolder.set();
            timeHolder.print();
        });
        t2.start();
        t2.join();
        
        timeHolder.print();
        
        timeHolder.set();
        timeHolder.print();
    }

}


This gave below output.

main : 1541956810082
Thread-0 : 1541956810085
main : 1541956810082
Thread-1 : 1541956810086
main : 1541956810082
main : 1541956810086


Notice how each thread is having it's own value meaning threads can't see each other's value.



Comments