Reputation: 49432
Can we set more than one object in a ThreadLocal
?
Upvotes: 6
Views: 6336
Reputation: 729
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.
Upvotes: 1
Reputation: 533820
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>();
}
});
Upvotes: 6
Reputation: 328770
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.
Upvotes: 16