Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple objects in a ThreadLocal

Can we set more than one object in a ThreadLocal ?

like image 818
AllTooSir Avatar asked Jan 09 '13 17:01

AllTooSir


2 Answers

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.

like image 115
Aaron Digulla Avatar answered Sep 22 '22 13:09

Aaron Digulla


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>();
     }
});
like image 38
Peter Lawrey Avatar answered Sep 22 '22 13:09

Peter Lawrey