Question

Can we set more than one object in a ThreadLocal ?

Was it helpful?

Solution

A thread local is a local variable of the current thread; so each thread gets exactly one value. But the value can be an instance, so you can put a map in there, for example or a custom type which collects all the values that you want.

OTHER TIPS

You can have multiple ThreadLocal and you can have an object in it which contains multiple objects.

e.g.

final ThreadLocal<Map<String, String>> localProperties = new ThreadLocal<Map<String, String>>() {
     public Map<String, String> initialValue() {
           return new LinkedHashMap<String, String>();
     }
});

We can create multiple ThreadLocal objects in a single Thread and access it using a particular ThreadLocal object's get() method.

Actually a ThreadLocal has a static inner class called ThreadLocalMap and its a customized hashmap, where key in this customized map is ThreadLocal object and value is value to be stored.

Every thread holds the reference of this threadLocalMap object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top