Prev Next

Java / Java ThreadLocal

Initialize ThreadLocal value for all instances/threads.

Values initialized using set() method is visible to that particular thread.

However without using set() method, we could initialize the value for all the instances of ThreadLocal object by subclassing ThreadLocal class and overriding the initialValue() method. See the below example.

private ThreadLocal threadLocalVar = new ThreadLocal<String>() {
    @Override protected String initialValue() {
        return "initialized value.";
    }
}; 

With the initial value being set, all threads will see the same value "initialized value" when calling get() method until set() method gets invoked.

More Related questions...

Show more question and Answers...


Comments & Discussions