Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize ThreadLocal objects in Java

I'm having an issue where I'm creating a ThreadLocal and initializing it with new ThreadLocal . The problem is, I really conceptually just want a persistent list that lasts the life of the thread, but I don't know if there's a way to initialize something per-thread in Java.

E.g. what I want is something like:

ThreadLocal static {   myThreadLocalVariable.set(new ArrayList<Whatever>()); } 

So that it initializes it for every thread. I know I can do this:

private static Whatever getMyVariable() {   Whatever w = myThreadLocalVariable.get();   if(w == null) {     w = new ArrayList<Whatever>();     myThreadLocalVariable.set(w);   }   return w;  } 

but I'd really rather not have to do a check on that every time it's used. Is there anything better I can do here?

like image 349
B T Avatar asked Mar 12 '13 18:03

B T


People also ask

What is ThreadLocal in Java?

The ThreadLocal class is used to create thread local variables which can only be read and written by the same thread. For example, if two threads are accessing code having reference to same threadLocal variable then each thread will not see any modification to threadLocal variable done by other thread.

What is the purpose of declaring a variable of type ThreadLocal?

It enables you to create variables that can only be read and write by the same thread. If two threads are executing the same code and that code has a reference to a ThreadLocal variable then the two threads can't see the local variable of each other.

Can ThreadLocal be static?

ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

How is ThreadLocal implemented?

The implementation of ThreadLocalMap is not a WeakHashMap , but it follows the same basic contract, including holding its keys by weak reference. Essentially, use a map in this Thread to hold all our ThreadLocal objects.


1 Answers

You just override the initialValue() method:

private static ThreadLocal<List<String>> myThreadLocal =     new ThreadLocal<List<String>>() {         @Override public List<String> initialValue() {             return new ArrayList<String>();         }     }; 
like image 66
Jon Skeet Avatar answered Sep 20 '22 21:09

Jon Skeet