当前位置:网站首页>A classic JVM class loaded interview question class singleton{static singleton instance = new singleton(); private singleton() {}

A classic JVM class loaded interview question class singleton{static singleton instance = new singleton(); private singleton() {}

2022-06-28 09:22:00 A bowl of humble powder

One 、 subject

Almost the same code , There are two cases :

Situation 1 :new SingleTon() rearwards , And what you get is :count1 = 1 and count2 = 1

Situation two :new SingleTon() in front , And what you get is :count1 = 1 and count2 = 0


 【 ask 】 Please give us a brief introduction , Why the output results of these two cases are different ?

Two 、 analysis

The main knowledge involved here is ,JVM Class loading mechanism of .

1、 The life cycle of a class : load ->  verification ->  Get ready ->  analysis ->  initialization ->  Use ->  uninstall , And verification , Preparation and parsing can be classified as the connection phase .

2、 When calling a static method in a class getSingleTon() when , Will trigger class initialization .

(1) For case one :

1) Connection phase , Will assign initial values to static variables , At this time count1=0,count2=0;

2) Then the initialization phase , Code execution from top to bottom , Assignment operations and static code blocks , At this time count1=0,count2=0;

Create objects SingleTon after , Yes count1 and count2 Conduct ++, Last count1=1,count2=1.

(2) For case two :

1) Connection phase , It is also a static variable that gives an initial value , It's the same time count1=0,count2=0;

2) Initialization phase , Execute code from top to bottom , Create the object first , Yes count1 and count2 Conduct ++, At this time count1=1,count2=1; then  public static int  count1 Yes count1 There is no assignment , At this time count1 Or is it equal to 1, however count2 Assigned a value to 0, At this time count2=0, So the final output count1=1,count2=0


【 Code 】

class SingleTon{
    private static SingleTon singleTon = new SingleTon();
    public static int  count1;
    public static int  count2 = 0;

    private SingleTon(){
        count1++;
        count2++;
    }
    public static  SingleTon getSingleTon(){
        return singleTon;
    }
}

public class ClassLoaderTest {
    public static void main(String[] args) {
        SingleTon.getSingleTon();
        System.out.println("count1 = "+ SingleTon.count1);
        System.out.println("count2 = "+ SingleTon.count2);
    }
}

原网站

版权声明
本文为[A bowl of humble powder]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202161350179268.html