undefinedfix
Sign in

How to initialize static variables?

Varun edited in Sat, 24 Sep 2022

For example,

class ThreadLocalVar {
  static ThreadLocal<String> clientId = new ThreadLocal<>()
  static ThreadLocal<String> source = new ThreadLocal<>()
  ...
}

There are several ThreadLocal, which can only be initialized when some of them are used. What should I do?

4 Replies
Bindu
commented on Sat, 24 Sep 2022

ThreadLocal initialization cost is not high, do lazy loading is not significant, do not do

JC1
commented on Sun, 25 Sep 2022

Separate into multiple inner classes

MikeyBroski
commented on Sun, 25 Sep 2022

Change static variable to static method, keep it with inner class

import org.junit.Test;

public class HolderTest {

    @Test
    public void testLazy(){
        //获取clientId时,source会先初始化,因为静态变量要先初始化
        System.out.println("1.get client");
        ThreadLocalVar.clientId().get();

        System.out.println("2.get source");
        ThreadLocalVar.source.get();
        //输出:
        // 1.get client
        // source initialized
        // clientId initialized
        // 2.get source
    }

    @Test
    public void testLazy2(){

        //获取source时,clientId不会初始化,因为Holder类只有用时才初始化
        System.out.println("1.get source");
        ThreadLocalVar.source.get();
        System.out.println("2.get client");
        ThreadLocalVar.clientId().get();
        //输出
        // 1.get source
        // source initialized
        // 2.get client
        // clientId initialized
    }

}

    class MyObj extends   ThreadLocal<String>{
        public MyObj(String name) {
            System.out.println(name+" initialized");
        }
    }

    class ThreadLocalVar {
        public static ThreadLocal<String> source = new MyObj("source");

        public static ThreadLocal clientId(){
            return IntiailizationOnDemandClassHolder.clientId;
        }

        private static class IntiailizationOnDemandClassHolder{
            private static final ThreadLocal<String> clientId = new MyObj("clientId");

        }
    }
gjotc
commented on Sun, 25 Sep 2022

Take a look at this, I believe you will understand: https://www.ixigua.com/6872736339528417792/