Friday, 30 January 2015

ThreadLocal for thread saferty

Some code I saw recently that is really a kind of concurrency pattern in Java

Problems and Constraints 

There is an implementation of an interface that is not thread safe. You would like to use it in a multi threaded scenario without modifying the interface.

public interface Calculator {
    public int calculate(int input) ;

public class NonThreadSafeCalculatorImpl implements Calculator {
    public int calculate(int input) {
        // non thread safe logic here
        // ...
An instance of NonThreadSafeCalculatorImplcan't be safely shared by multiple threads.

Implement the interface by delegating to a ThreadLocal that wraps the unsafe implementation

public class ThreadSafeCalculatorImpl implements Calculator {

    private static final ThreadLocal threadLocal = new ThreadLocal() {
        protected Calculator initialValue() {
            return new NonThreadSafeCalculatorImpl();

    public int calculate(int input) {
        return threadLocal.get().calculate(input);
An instance of ThreadSafeCalculatorImpl can be safely shared by multiple threads.

No comments:

Post a Comment