When and how should I use a ThreadLocal variable?

前端 未结 25 2265
再見小時候
再見小時候 2020-11-22 12:35

When should I use a ThreadLocal variable?

How is it used?

25条回答
  •  -上瘾入骨i
    2020-11-22 13:15

    Since Java 8 release, there is more declarative way to initialize ThreadLocal:

    ThreadLocal local = ThreadLocal.withInitial(() -> "init value");
    

    Until Java 8 release you had to do the following:

    ThreadLocal local = new ThreadLocal(){
        @Override
        protected String initialValue() {
            return "init value";
        }
    };
    

    Moreover, if instantiation method (constructor, factory method) of class that is used for ThreadLocal does not take any parameters, you can simply use method references (introduced in Java 8):

    class NotThreadSafe {
        // no parameters
        public NotThreadSafe(){}
    }
    
    ThreadLocal container = ThreadLocal.withInitial(NotThreadSafe::new);
    

    Note: Evaluation is lazy since you are passing java.util.function.Supplier lambda that is evaluated only when ThreadLocal#get is called but value was not previously evaluated.

提交回复
热议问题