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?
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.
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.
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).
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.
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>(); } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With