Singleton mode and multithreading

Source: Internet
Author: User

A hungry man mode is also known as the immediate loading mode, including the above is very urgent

That is, the object was created when the class was Used.

PackageLock; public classEhansingleton {/*a hungry man load mode/immediate load mode*/            //Initializing Constructors    PrivateEhansingleton () {}Private  StaticEhansingleton Ehan =NewEhansingleton ();  public StaticEhansingleton getinstance () {Try{thread.sleep ( the);//Convenient multi-threading testing}Catch(interruptedexception E) {e.printstacktrace (); }          returnehan; }}

Then we use a simple multithreaded test

PackageLock; public classMyThread extends Thread{@Override public voidRun () {System. out. println (ehansingleton.getinstance (). hashcode ()); }      public Static voidmain (string[] Args) {MyThread M1=NewMyThread (); MyThread M12=NewMyThread (); MyThread M13=NewMyThread ();            M1.start ();            M12.start ();    M13.start (); }}

126720696

126720696
126720696

The result is that the hashcode value of each object is the same, indicating that the pattern is in accordance with the Singleton pattern, which is the immediate loading type of the singleton design Pattern.

Second singleton mode lazy Mode/lazy load

This is the only way to invoke this instance when a method is Called.

PackageLock; public classLanhansingleton {/*Lazy Mode/lazy Load*/        //Privatization Constructors    PrivateLanhansingleton () {}Private  StaticLanhansingleton lanhansingleton;  public  StaticLanhansingleton getinstance () {if(lanhansingleton = =NULL){                Try{thread.sleep ( the); Lanhansingleton=NewLanhansingleton (); } Catch(interruptedexception E) {e.printstacktrace (); }                         }          returnlanhansingleton; }}

I'm using multithreading to test if the value of each Object's hashcode is consistent

PackageLock; public classMyThread extends Thread{@Override public voidRun () {System. out. println (lanhansingleton.getinstance (). hashcode ()); }      public Static voidmain (string[] Args) {MyThread M1=NewMyThread (); MyThread M12=NewMyThread (); MyThread M13=NewMyThread ();            M1.start ();            M12.start ();    M13.start (); }}

126720696
137014984
1638443495

The results of the test found that this is not in the singleton mode, they are not the same object, but a few different objects, so this lazy mode in a single thread is consistent with the singleton mode, but in a multithreaded environment is not consistent with the singleton mode

Think of here, you will certainly think of the synchrinized keyword, we are looking at the effect

PackageLock; public classLanhansingleton {/*Lazy Mode/lazy Load*/        //Privatization Constructors    PrivateLanhansingleton () {}Private  StaticLanhansingleton lanhansingleton;  publicSynchronizedStaticLanhansingleton getinstance () {if(lanhansingleton = =NULL){                Try{thread.sleep ( the); Lanhansingleton=NewLanhansingleton (); } Catch(interruptedexception E) {e.printstacktrace (); }                         }          returnlanhansingleton; }}

Operation Result:

1638443495
1638443495
1638443495

It is found that this can solve the problem caused by the different objects of multithreading, but this method is not good, This method is very inefficient, it is necessary to wait until the last thread release lock to get the object

Synchronous method is to hold the lock on the whole method, this is too slow for efficiency, we also think of using synchronous block, then we are trying to

PackageLock; public classLanhansingleton {/*Lazy Mode/lazy Load*/        //Privatization Constructors    PrivateLanhansingleton () {}Private  StaticLanhansingleton lanhansingleton;  public   StaticLanhansingleton getinstance () {Try{synchronized (lanhansingleton).class) {                 if(lanhansingleton = =NULL) {thread.sleep ( the); Lanhansingleton=NewLanhansingleton (); }            }                             } Catch(interruptedexception E) {e.printstacktrace (); }                        returnlanhansingleton; }}

In fact, this effect and the previous effect is similar, the efficiency is relatively slow, and synchronous method synchronized is synchronous operation

The best way here is the DCL double check lock mechanism

PackageLock; public classLanhansingleton {/*Lazy Mode/lazy Load*/        //Privatization Constructors    PrivateLanhansingleton () {}Private  StaticLanhansingleton lanhansingleton;  public   StaticLanhansingleton getinstance () {Try {                             if(lanhansingleton = =NULL) {synchronized (lanhansingleton.class) {                         if(lanhansingleton = =NULL){                             Lanhansingleton=NewLanhansingleton (); }                                             }               }                          } Catch(interruptedexception E) {e.printstacktrace (); }                        returnlanhansingleton; }}

There is also the way in which the inner class

PackageLock; import Java.io.objectstreamexception;import java.io.Serializable; public classMyObject implements serializable{PrivateMyObject () {}Private Static classmyobjecthander{Private StaticMyObject MyObject =NewMyObject (); }             public  StaticMyObject getinstance () {returnmyobjecthander.myobject; }            //public MyObject readresolve () throws objectstreamexception {//System.out.println ("this method is called");//return myobjecthander.myobject;//      }      }

This is the inner class way, but this internal way still has the problem of ken, although this can reach the case of multi-threaded Singleton mode, but if encountered in the case of serialization will violate the criteria of the singleton mode ....

The method of commenting is to serialize the provided

PackageLock; import Java.io.objectstreamexception;import java.io.Serializable; public classMyObject implements serializable{Private StaticFinalLongSerialversionuid =1L; PrivateMyObject () {}Private Static classmyobjecthander{Private StaticFinal MyObject MyObject =NewMyObject (); }             public  StaticMyObject getinstance () {returnmyobjecthander.myobject; }                  protectedMyObject readresolve () throws Objectstreamexception {System. out. println ("This method is Called."); returnmyobjecthander.myobject; }      }

PackageLock; import Java.io.file;import java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import java.io.ObjectOutputStream; public classChecksingletonhashcode { public Static voidmain (string[] Args) {Try{MyObject MyObject=myobject.getinstance (); FileOutputStream OS=NewFileOutputStream (NewFile ("D://lol.txt")); ObjectOutputStream Oos=NewObjectOutputStream (os);                  Oos.writeobject (myObject);                  Oos.close ();                  Os.close (); System. out. println (myobject.hashcode ()); } Catch(filenotfoundexception E) {e.printstacktrace (); } Catch(ioexception E) {e.printstacktrace (); }                     Try{fileinputstream is=NewFileInputStream (NewFile ("D://lol.txt")); ObjectInputStream Ois=NewObjectInputStream ( is); MyObject MyObject=(MyObject) Ois.readobject ();                  Ois.close ();  is. Close (); System. out. println (myobject.hashcode ()); } Catch(filenotfoundexception E) {e.printstacktrace (); }Catch(classnotfoundexception |IOException E)            {e.printstacktrace (); }                            }}

Singleton mode and multithreading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.