As you know, Java singleton mode is not singleton mode

When we search the singleton mode, we can see many examples, such as lazy and hungry, as follows:

When we write a main method to test the above singleton mode, we find the following:

It seems that there is no problem. It seems that that's the case. The constructor is called only once, and the same object is returned twice.

At that time, this was the case of single thread. What if it was the case of multiple threads, as follows:

From the results, we can see that unfortunately, the constructor is called three times, that is, three times of new singleton() calls, and the printed results are also different instances.

Therefore, our common single case is unreliable. It is OK to add the synchronized keyword to the getInstance () method.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>