How to initialize ThreadLocal objects in Java

后端 未结 3 1485
猫巷女王i
猫巷女王i 2020-12-06 04:21

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

3条回答
  •  情歌与酒
    2020-12-06 05:04

    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 functional interface.

提交回复
热议问题