Java multithreaded Programming 6--Singleton mode and multithreading--using static built-in classes, (inverse) serialization, static block, enum Enum data class implementation

Source: Internet
Author: User

In front of the DCL can be used to solve the multi-threaded singleton mode of non-threading security, although the look is very perfect, but there are some problems, the specific analysis look at this article: http://blog.csdn.net/ochangwen/article/details/51348078

Of course, the same effect can be achieved by other means.

1, using static built-in class to implement a singleton mode

public class Singleton {    /* private construction method to prevent instantiation of *    /Private Singleton () {    }/    * Here use an inner class to maintain the singleton */    private Static class Singletonfactory {        private static Singleton instance = new Singleton ();    }    /* Get instance *    /public static Singleton getinstance () {        return singletonfactory.instance;}    }
Custom Threads
public class MyThread extends Thread {    @Override public    void Run () {        System.out.println ( Singleton.getinstance (). Hashcode ());}    }
public class Run {public    static void Main (string[] args) throws ParseException {        MyThread t1 = new MyThread (); 
   mythread t2 = new MyThread ();        MyThread t3 = new MyThread ();        T1.start ();        T2.start ();        T3.start ();    }}
1756075494
1756075494
1756075494

2, serialization and deserialization of the single-instance mode implementation

Static built-in classes can achieve thread-safety problems, but if you encounter a serialized object, the result is run in the default way, or multiple cases.

public class Singleton implements serializable{    /* Private construction method to prevent instantiation of *    /Private Singleton () {    }/    * Here an inner class is used to maintain the singleton *    /private static class Singletonfactory {        private static Singleton instance = new Singleton (); 
   }    /* Get instance *    /public static Singleton getinstance () {        return singletonfactory.instance;    }    /* If the object is used for serialization, you can ensure that the object is consistent before and after serialization *    /Protected Object Readresolve () throws objectstreamexception{        SYSTEM.OUT.PRINTLN ("Call the Readresolve method");        return getinstance ();    }}
Create the business class Saveandread with the following code:
public class Saveandread {public static void main (string[] args) {try {Singleton Singleton = Sing            Leton.getinstance ();            FileOutputStream fosref = new FileOutputStream (New File ("MySingletonFIle.txt"));            ObjectOutputStream oosref = new ObjectOutputStream (FOSREF);            Oosref.writeobject (singleton);            Oosref.close ();            Fosref.close ();        System.out.println (Singleton.hashcode ());        } catch (FileNotFoundException e) {e.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();            } try{FileInputStream fisref = new FileInputStream (New File ("MySingletonFIle.txt"));            ObjectInputStream iosref = new ObjectInputStream (FISREF);            Singleton Singleton = (Singleton) iosref.readobject ();            Iosref.close ();            Fisref.close ();        System.out.println (Singleton.hashcode ());          } catch (FileNotFoundException e) {  E.printstacktrace ();        } catch (IOException e) {e.printstacktrace ();        } catch (ClassNotFoundException e) {e.printstacktrace (); }    }}
723635264
Called the Readresolve method
723635264
If the Readresolve method in the Singleton class is commented out, the result will be the same.
1484511730
588729095
Not the same object

----------------------------------------------------------------------------------------------------

3. Use static code block to implement Singleton mode

The code in the static code block is executed when the class is used, so you can apply this feature of the static code block to implement the singleton design pattern.

public class Singleton {/    * * holds a private static instance that is protected from reference and is assigned null here to enable lazy loading */    private static Singleton instance = null;    /* Private construction method to prevent instantiation of *    /Private Singleton () {    }    static {        instance = new Singleton ();    }    public static Singleton getinstance () {        return instance;    }}
The custom thread mythread and the run class do not change, and the result is as follows:
1032010069
1032010069
1032010069

4. Using enum enum data type to implement Singleton mode

enum enum and static code blocks are similar in nature, when using an enumeration class, the construction method is automatically called, or it can be applied to implement a singleton design pattern, the most classic is the database connection.

public enum Singleton {    connectionfactory;    Private Connection Connection;    Private Singleton () {        try {            System.out.print ("called Singleton's construct! ");            String url = "Jdbc:sqlserver://localhost:1079;databasenme=db";            String username = "123456";            String password = "123456";            String drivername = "Com.microsoft.sqlserver.jdbc.SQLServerDriver";            Class.forName (drivername);            Connection = drivermanager.getconnection (URL, username,password);        } catch (ClassNotFoundException e) {            e.printstacktrace ();        } catch (SQLException e) {            e.printstacktrace () ;        }    }    Public Connection getconnection () {        return Connection;    }}
The Run method of the custom line thread is modified to:
    public void Run () {        System.out.println (singleton.connectionfactory.                Getconnection (). Hashcode ());    }
1032010069
1032010069
1032010069

5. Perfect using Enum enumeration to implement Singleton mode

The preceding section exposes enumerated classes, violating the "single principle of responsibility", which is perfected below.

public class Singleton {public enum Mysingleton {connectionfactory;        Private Connection Connection; Private Mysingleton () {try {System.out.print ("called Singleton's construct!                ");                String url = "Jdbc:sqlserver://localhost:1079;databasenme=db";                String username = "123456";                String password = "123456";                String drivername = "Com.microsoft.sqlserver.jdbc.SQLServerDriver";                Class.forName (drivername);            Connection = drivermanager.getconnection (URL, username,password);            } catch (ClassNotFoundException e) {e.printstacktrace ();            } catch (SQLException e) {e.printstacktrace ();        }} public Connection getconnection () {return Connection;    }} public static Connection getconnection () {return MySingleton.connectionFactory.getConnection (); }}

Java multithreaded Programming 6--Singleton mode and multithreading--using static built-in classes, (inverse) serialization, static block, enum Enum data class implementation

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.