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 last
Your solution is fine. A little simplification:
private static Whatever getMyVariable()
{
Whatever w = myThreadLocalVariable.get();
if(w == null)
myThreadLocalVariable.set(w=new Whatever());
return w;
}
In Java 8, we are able to do:
ThreadLocal> myThreadLocal = ThreadLocal.withInitial(ArrayList::new);
which uses the Supplier