AllTooSir
AllTooSir

Reputation: 49432

Multiple objects in a ThreadLocal

Can we set more than one object in a ThreadLocal ?

Upvotes: 6

Views: 6336

Answers (3)

Jatinder Pal
Jatinder Pal

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

Peter Lawrey
Peter Lawrey

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

Aaron Digulla
Aaron Digulla

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

Related Questions