1

I'm using a InheritableThreadlocal with HashMap for storing all my threadlocals.

class MyThreadLocalMap {
    private final static ThreadLocal<HashMap<String, Object>> THREAD_VARIABLES = new InheritableThreadLocal<HashMap<String, Object>>() {
        @Override
        protected HashMap<String, Object> initialValue() {
            return new HashMap<>();
        }
    };

    public static Object get(String name) {
        return THREAD_VARIABLES.get().get(name);
    }

    public static Object set(String name, Object value) {
        Object currentValue = get(name);
        THREAD_VARIABLES.get().put(name, value);
        return currentValue;
    }
}

This worked fine until a strange bug popped out last day.

I'm using a tomcat server to run my web application. I used ScheduledThreadPoolExecutor to create a threadpool and run a task in multiple threads. The shortform of my code looks something similar to this.

MyThreadLocalMap.set("MyKey", 1);
....
....
Object obj = MyThreadLocalMap.get("MyKey");
if(!Integer.valueOf(1).equals(obj))
    throw new Exception("threadlocal mismatch!");
....
....
MyThreadLocalMap.set("MyKey", null);

The above code will get executed in multiple threads, and since I'm using threadpool, the same threads will get reused.

Strangely, the "threadlocal mismatch" exception was thrown in one of the threads, after around 5 threads completed execution successfully!

My prime suspect is the use of InheritableThreadLocal (which is infamous for memory leaks)

I tried and retried to reproduce the issue in development servers, which I couldn't. And I don't want to risk testing this in production server.

1 Answer 1

2

Your Map is instantiated in the parent Thread. InheritedThreadLocal value is "taken down" to the child threads.

While multiple child threads are potentially executed in parallel esp. the shown part, one thread may set "MyKey" to null while another child thread is reading it.

So this is a real problem. You should synchronize the code between setting and reading. Or use a normal ThreadLocal.

Btw. you should sync access to the map.

1
  • No I never accessed MyThreadLocalMap from parent thread. To be specific the thread pool initializing code is in a different jar file. So I believe each child threads should have its own copy of the map.
    – Jasir
    Feb 16, 2018 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.