如何在Java中初始化ThreadLocal对象

如何在Java中初始化ThreadLocal对象

问题描述:

我遇到了一个问题,我正在创建一个ThreadLocal并使用新的ThreadLocal初始化它。问题是,我在概念上只想要一个持久的列表,这个列表会延续线程的生命,但我不知道是否有办法在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.

例如我想要的是:

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?

你只需覆盖 initialValue()方法:

private static ThreadLocal<List<String>> myThreadLocal =
    new ThreadLocal<List<String>>() {
        @Override public List<String> initialValue() {
            return new ArrayList<String>();
        }
    };