People all over the world know that the definition of a class in a singleton design pattern is divided into two types: lazy and a hungry man, but today is not to compare them horizontally. In fact, no matter how beautiful the code of the A Hungry man class looks, its efficiency is always less efficient than the lazy one in real-world development. However, in the written test and the interview, the idle rate can be said to be more than a hungry man-type do not know where to go, so it is very necessary to fully understand it.
A Hungry man type:
class Single1 { int num = 1; Private Static New Single1 (); Private Single1 () {} Static Single1 GetInstance1 () { return single1; }}
The simplest type of loafer:
class Single2
{ int num = 2; private static Single2 single2 = Span style= "COLOR: #0000ff" >null ; private Single2 () {} static Single2 GetInstance2 () {//If two threads are accessed concurrently, it is possible to generate two instances that do not conform to a single Example pattern requirements
if (single2 = = null ) single2 = new Single2 (); return Single2;
}}
However, such a class definition is actually thread insecure. As the note says, because of the uncertainty of the thread, it is not possible to confirm that they are accessing Single2 = new Single2 (), when a Single2 instance has been generated. If you write such a code in an interview, you will often be asked if the improvement will make it thread safe. According to the general idea, we make the following improvements to the code:
classSingle2 {intnum = 2; Private StaticSingle2 Single2 =NULL; PrivateSingle2 () {}StaticObject obj =NewObject (); Create a sync lock objectStaticSingle2 GetInstance2 () {synchronized(obj)//sync lock to ensure that only one thread at a time can access the internal module {if(Single2 = =NULL) Single2=NewSingle2 (); returnSingle2; } }}
The code has been improved to solve the thread insecurity problem, but may be asked again: This can solve the thread insecurity, but also reduce the efficiency of the program, how to improve the code? In fact, add a conditional judgment statement on the outer layer.
classSingle2 {intnum = 2; Private StaticSingle2 Single2 =NULL; PrivateSingle2 () {}StaticObject obj =NewObject (); StaticSingle2 GetInstance2 () {if(Single2 = =NULL) { synchronized(obj) {if(Single2 = =NULL) Single2=NewSingle2 (); } } returnSingle2; }}
Perfect, estimated there is nothing to ask, test it.
Public class single{ publicstaticvoid main (string[] args) { = Single1.getinstance1 (); = Single2.getinstance2 (); System.out.println (s1.num+ "..." +s2.num);} }
Output Result:
1..2
No problem!
Discussion on the definition of lazy class in Java single-case design pattern