concept:
Singleton pattern in Java is a common design pattern. Singleton pattern is divided into three types: lazy singleton, hungry singleton, and registered singleton.
The singleton mode has the following characteristics:
1. There can only be one instance in a singleton class.
2. The singleton class must create its own unique instance.
3. The singleton class must provide this instance to all other objects.
Singleton pattern ensures that a class has only one instance, and instantiates it itself and provides this instance to the entire system. In computer systems, driver objects for thread pools, caches, log objects, dialog boxes, printers, and graphics cards are often designed as singletons. These applications have more or less the functionality of a resource manager. Each computer can have several printers, but only one Printer Spooler can be available to avoid two print jobs being output to the printer at the same time. Each computer can have several communication ports, and the system should centrally manage these communication ports to avoid one communication port being called simultaneously by two requests. In short, choosing a singleton model is to avoid inconsistent states and avoid political bullishness.
Here are two types of introductions: lazy and hungry
1. Load immediately/hungry style
Before calling the method, the instance has been created, code:
package com.weishiyao.learn.day8.singleton.ep1;public class MyObject { // Loading now ==Evil mode private static MyObject myObject = new MyObject(); private MyObject() { } public static MyObject getInstance() { // This code version is loading now // The disadvantage of this version of the code is that there cannot be other instance variables // Because the getInstance() method is not synchronized // Therefore, non-thread-safe issues may occur return myObject; }} Create a thread class
package com.weishiyao.learn.day8.singleton.ep1;public class MyThread extends Thread { @Override public void run() { System.out.println(MyObject.getInstance().hashCode()); }} Create a run class
package com.weishiyao.learn.day8.singleton.ep1;public class Run { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); MyThread t3 = new MyThread(); t1.start(); t2.start(); t3.start(); }} Running results
167772895
167772895
167772895
hashCode is the same value, which means that the object is also the same, which means that the instant loading mode is implemented.
2. Lazy loading/lazy
The instance will be created after the method is called. The implementation plan can be to put instantiation into the parameterless constructor, so that an instance of the object will be created only when the method is called. Code:
package com.weishiyao.learn.day8.singleton.ep2;public class MyObject { private static MyObject myObject; private MyObject() { } public static MyObject getInstance() { // Delay loading if (myObject != null) { } else { myObject = new MyObject(); } return myObject; }} Create a thread class
package com.weishiyao.learn.day8.singleton.ep2;public class MyThread extends Thread { @Override public void run() { System.out.println(MyObject.getInstance().hashCode()); }} Create a run class
package com.weishiyao.learn.day8.singleton.ep2;public class Run { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); }}Running results
167772895
Although an instance of an object is taken, if it is in a multi-threaded environment, multiple instances will occur, which is not a singleton pattern
Run the test class
package com.weishiyao.learn.day8.singleton.ep2;public class Run { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); MyThread t3 = new MyThread(); MyThread t4 = new MyThread(); MyThread t5 = new MyThread(); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}Running results
980258163
1224717057
1851889404
188820504
1672864109
Since there is a problem, we need to solve the problem. Multithreaded solution in lazy mode, code:
The first solution, most commonly, add synchronized, and synchronized can be added to different positions
The first method locks
package com.weishiyao.learn.day8.singleton.ep3;public class MyObject { private static MyObject myObject; private MyObject() { } synchronized public static MyObject getInstance() { // Delay loading try { if (myObject != null) { } else { // Simulate some preparation before creating an object Thread.sleep(2000); myObject = new MyObject(); } } catch (InterruptedException e) { e.printStackTrace(); } return myObject; }}This synchronized synchronization scheme results in too inefficient and the entire method is locked
The second synchronized usage scheme
package com.weishiyao.learn.day8.singleton.ep3;public class MyObject { private static MyObject myObject; private MyObject() { } public static MyObject getInstance() { // Delay loading try { synchronized (MyObject.class) { if (myObject != null) { } else { // Simulate some preparation work before creating an object Thread.sleep(2000); myObject = new MyObject(); } } } catch (InterruptedException e) { e.printStackTrace(); } return myObject; }} This method is also very low-efficiency. All codes in the method are locked. You only need to lock the key code. The third synchronized usage plan
package com.weishiyao.learn.day8.singleton.ep3;
public class MyObject { private static MyObject myObject; private MyObject() { } public static MyObject getInstance() { // Delay loading try { if (myObject != null) { } else { // Simulate some preparation before creating the object Thread.sleep(2000); synchronized (MyObject.class) { myObject = new MyObject(); } } } catch (InterruptedException e) { e.printStackTrace(); } return myObject; }}This seems to be the best solution, but after running it, I found that it is actually non-thread-safe
result:
1224717057
971173439
1851889404
1224717057
1672864109
Why?
Although the statement that creates an object is locked, only one thread can complete the creation at a time, after the first thread comes in to create the Object object, the second thread can still continue to create it, because we only lock the creation statement, this problem solution
package com.weishiyao.learn.day8.singleton.ep3;public class MyObject { private static MyObject myObject; private MyObject() { } public static MyObject getInstance() { // Delay loading try { if (myObject != null) { } else { // Simulate some preparation before creating an object Thread.sleep(2000); synchronized (MyObject.class) { if (myObject == null) { myObject = new MyObject(); } } } } catch (InterruptedException e) { e.printStackTrace(); } return myObject; }}Just add another judgment to the lock to ensure a singleton. This is the DCL double check mechanism
The results are as follows:
1224717057
1224717057
1224717057
1224717057
1224717057
3. Use built-in static classes to implement single cases
Main code
package com.weishiyao.learn.day8.singleton.ep4;public class MyObject { // Inner class method private static class MyObjectHandler { private static MyObject myObject = new MyObject(); } public MyObject() { } public static MyObject getInstance() { return MyObjectHandler.myObject; }} Thread class code
package com.weishiyao.learn.day8.singleton.ep4;public class MyThread extends Thread { @Override public void run() { System.out.println(MyObject.getInstance().hashCode()); }} Run class
package com.weishiyao.learn.day8.singleton.ep4;public class Run { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); MyThread t3 = new MyThread(); MyThread t4 = new MyThread(); MyThread t5 = new MyThread(); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}result
1851889404
1851889404
1851889404
1851889404
1851889404
Through internal static classes, a thread-safe singleton pattern is obtained
IV. Serialize and deserialize singleton patterns
Built-in static classes can achieve thread safety problems, but if you encounter serialized objects, the result obtained by using the default method is still multiple cases.
MyObject Code
package com.weishiyao.learn.day8.singleton.ep5;import java.io.Serializable;public class MyObject implements Serializable { /** * */ private static final long serialVersionUID = 888L; // Inner class method private static class MyObjectHandler { private static MyObject myObject = new MyObject(); } public MyObject() { } public static MyObject getInstance() { return MyObjectHandler.myObject; } // protected MyObject readResolve() {// System.out.println("The readResolve method was called!");// return MyObjectHandler.myObject;// }} Business
package com.weishiyao.learn.day8.singleton.ep5;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 class SaveAndRead { public static void main(String[] args) { try { MyObject myObject = MyObject.getInstance(); FileOutputStream fosRef = new FileOutputStream(new File("myObjectFile.txt")); ObjectOutputStream oosRef = new ObjectOutputStream(fosRef); oosRef.writeObject(myObject); oosRef.close(); fosRef.close(); System.out.println(myObject.hashCode()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } FileInputStream fisRef; try { fisRef = new FileInputStream(new File("myObjectFile.txt")); ObjectInputStream iosRef = new ObjectInputStream(fisRef); MyObject myObject = (MyObject) iosRef.readObject(); iosRef.close(); fisRef.close(); System.out.println(myObject.hashCode()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }}result
970928725
1099149023
Two different hashCodes prove that they are not the same object. Solution, add the following code
protected MyObject readResolve() { System.out.println("The readResolve method was called!"); return MyObjectHandler.myObject; }Called during deserialization, you can get the same object
System.out.println(myObject.readResolve().hashCode());
result
1255301379
The readResolve method was called!
1255301379
The same hashCode proves that the same object is obtained
5. Use static code blocks to implement single case
The code in the static code block is already executed when using the class, so the feature of static code fast can be used to implement the simple profit mode.
MyObject class
package com.weishiyao.learn.day8.singleton.ep6;public class MyObject { private static MyObject instance = null; private MyObject() { super(); } static { instance = new MyObject(); } public static MyObject getInstance() { return instance; }} Thread class
package com.weishiyao.learn.day8.singleton.ep6;public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(MyObject.getInstance().hashCode()); } }} Run class
package com.weishiyao.learn.day8.singleton.ep6;public class Run { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); MyThread t3 = new MyThread(); MyThread t4 = new MyThread(); MyThread t5 = new MyThread(); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}Running results:
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
1678885403
The thread-safe singleton pattern is successfully obtained through the feature of only executing static code blocks once.
6. Use enum enum data types to implement singleton mode
The characteristics of enum enum and static code blocks are similar. When using enums, the constructor will be called automatically and can also be used to implement singleton mode.
MyObject class
package com.weishiyao.learn.day8.singleton.ep7;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public enum MyObject { connectionFactory; private Connection connection; private MyObject() { try { System.out.println("The construct of MyObject was called"); String url = "jdbc:mysql://172.16.221.19:3306/wechat_1?useUnicode=true&characterEncoding=UTF-8"; String name = "root"; String password = "111111"; String driverName = "com.mysql.jdbc.Driver"; Class.forName(driverName); connection = DriverManager.getConnection(url, name, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public Connection getConnection() { return connection; }} Thread class
package com.weishiyao.learn.day8.singleton.ep7;public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(MyObject.connectionFactory.getConnection().hashCode()); } }} Run class
package com.weishiyao.learn.day8.singleton.ep7;public class Run { public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); MyThread t3 = new MyThread(); MyThread t4 = new MyThread(); MyThread t5 = new MyThread(); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); }}Running results
Called the MyObject construct
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
56823666
The above writing method exposes the enumeration class, which violates the "single responsibility principle". You can use a class to wrap the enumeration.
package com.weishiyao.learn.day8.singleton.ep8;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class MyObject { public enum MyEnumSingleton { connectionFactory; private Connection connection; private MyEnumSingleton() { try { System.out.println("The construct of MyObject was called"); String url = "jdbc:mysql://172.16.221.19:3306/wechat_1?useUnicode=true&characterEncoding=UTF-8"; String name = "root"; String password = "111111"; String driverName = "com.mysql.jdbc.Driver"; Class.forName(driverName); connection = DriverManager.getConnection(url, name, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public Connection getConnection() { return connection; } } public static Connection getConnection() { return MyEnumSingleton.connectionFactory.getConnection(); }} Change the thread code
package com.weishiyao.learn.day8.singleton.ep8;public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(MyObject.getConnection().hashCode()); } }} As a result, the MyObject construct is called
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
1948356121
The above summarizes various situations and solutions encountered when combining the single-interest mode with multi-threading, so that it can be reviewed when used later.