A hungry man, lazy and enumerated _java of single case mode in Java implementation

Source: Internet
Author: User

Implementation of single case mode (5 kinds)

Common:

A Hungry man (thread-safe, call efficient, but not delay loading)
Lazy (thread safe, call efficiency is not high, can delay loading)

Other:

Dual detection Lock (due to the internal model of the JVM, occasional problems, do not establish use)
static internal class (thread safe, call efficient, but can delay loading)
Enum Single example (thread safe, call efficient, cannot delay loading)
A hungry man-type single example specific code is as follows:

Package Com.lcx.mode; 
 /** * * A hungry man singleton, regardless of the future use of this object, we started to create an instance of this object, * when needed to return the created instance object, so relatively hungry, so called the A Hungry man-style singleton. * @author qq1013985957 * * */public class Singletonhanger {private static final Singletonhanger instance = new Sin 
  Gletonhanger (); 
  Private Singletonhanger () {} public static Singletonhanger getinstance () {return instance; 
 }/** * Lazy Chinese-style single example, when you need a single instance object, you create a unique single Instance object, call it again later, and return the first created single Instance object * Initializes the static member to null and is created when a single instance is obtained, so it is called a lazy type. 
  * @author qq1013985957 * * */class singletonlazy{private static Singletonlazy instance = NULL; 
   Private Singletonlazy () {}/** * This method implements a single instance that cannot be used in multiple threads, and multiple lines can enter the If method at the same time, resulting in multiple single instance objects being generated. * @return */public static Singletonlazy GetInstance1 () {if (instance==null) {instance = new Singletonla 
    Zy (); 
  return instance; 
   /** * Everyone will think of synchronization, can be synchronized to achieve a single example of multithreading * But this method is not desirable, seriously affect performance, because each to take a single example to check the method, so you can only sync code block way to achieve synchronization. * @return */public static synchronized Singletonlazy GetInstance2() {if (instance==null) {instance = new Singletonlazy (); 
  return instance; /** * Using synchronized code blocks to determine if a single case exists, use a synchronized code block in a synchronized code block to check whether a single instance has been generated, * This is the online double check locking method * @return/Publ 
        IC Static synchronized Singletonlazy GetInstance3 () {if (instance==null) {synchronized (Singletonlazy.class) { 
        if (instance==null) {instance = new Singletonlazy (); 
  }} return instance; 
 }/** * * * Using enumerations to implement singleton patterns, is also the recommended way in effective JAVA * Based on the specific circumstances of the instantiation, to enumerate unfamiliar students, you can refer to my blog JAVA enumeration class preliminary understanding. 
 * Its benefits: more concise, free to provide a serialization mechanism, absolutely prevent multiple instantiation, even in the face of complex sequence and reflection attacks. 
  * @author qq1013985957 * */enum singletionenum{Singletionenum ("enumeration of single cases"); 
  Private String str; 
  Private Singletionenum (String str) {this.setstr (str); 
  Public String Getstr () {return str; 
  public void Setstr (String str) {this.str = str; 
 } 
   
}

The above single example mode is not tested, you can go to test, judge whether the object's hashcode is consistent to determine whether it is the same object.

The evil-Chinese, lazy-style way is also not to prevent reflection to implement multiple instances, by reflection, set the Accessible.setaccessible method can call the private constructor, you can modify the constructor, so that it is required to create a second instance when the exception thrown.

In fact, this does not guarantee the singleton, when serialized, deserialization is also possible to create a new instance and add the Readresolve () method to the singleton class to prevent it.
The Lazy Han-style single example code is as follows:

Package Com.lcx.mode; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import Java.io.FileOutputStream; 
Import Java.io.ObjectInputStream; 
Import Java.io.ObjectOutputStream; 
Import java.io.Serializable; 
Import Java.lang.reflect.Constructor; 
 
Import java.lang.reflect.InvocationTargetException; 
 /** * Lazy Chinese-style single example, when a single instance object is needed, the unique single Instance object is created, called again, and the first created single Instance object * Initializes static members to NULL and is created when a single instance is obtained, so it is called a lazy type. * @author qq1013985957 * * */public class Singleton implements serializable{/** * * * private static fin 
  Al long serialversionuid = -5271537207137321645l; 
  private static Singleton instance = NULL; 
  private static int i = 1; 
    Private Singleton () {/** * To prevent reflection attacks, only run call once constructor, second throw exception/if (i==1) {i++; 
    }else{throw new RuntimeException ("Only one constructor can be invoked"); 
     
  } System.out.println ("Call private constructor for Singleton"); /** * Using synchronized code blocks to determine if a single case exists, use a synchronized code block to check whether a single instance has been generated in the synchronized code block, * This is the online double check locking method * @return * *Ublic static synchronized Singleton getinstance () {if (instance==null) {synchronized (Singleton.class) { 
        if (instance==null) {instance = new Singleton (); 
  }} return instance; /** * * Prevents the deserialization from generating a new single Instance object, as effective Java book says this method prevents, details I do not understand * @return/private Object Readres 
  Olve () {return instance; 
    public static void Main (string[] args) throws Exception {test1 (); 
  Test2 (); /** * Test reverse sequence is still a single case mode * @throws Exception */public static void Test2 () throws exception{Singleto 
    n s = singleton.getinstance (); 
    ObjectOutputStream ObjectOutputStream = new ObjectOutputStream (New FileOutputStream ("E:\\singleton.txt")); 
    Objectoutputstream.writeobject (s); 
    ObjectInputStream ObjectInputStream = new ObjectInputStream (New FileInputStream ("E:\\singleton.txt")); 
    Object readobject = Objectinputstream.readobject (); Singleton S1 = (SingLeton) ReadObject; 
     
    System.out.println ("S.hashcode ():" +s.hashcode () + ", S1.hashcode ():" +s1.hashcode ()); 
    Objectoutputstream.flush (); 
    Objectoutputstream.close (); 
  Objectinputstream.close (); /** * Test Reflection Attack * @throws Exception/public static void Test1 () {Singleton s = Singleton.getinstan 
    CE (); 
    Class C = singleton.class; 
    Constructor Privateconstructor; 
      try {privateconstructor = C.getdeclaredconstructor (); 
      Privateconstructor.setaccessible (TRUE); 
    Privateconstructor.newinstance (); 
    catch (Exception e) {e.printstacktrace (); 
 } 
  } 
}

To verify the reflection attack results:

If you do not add the results of the Readresolve method:

Add the results of the Readresolve method:

Thank you for reading, I hope to help you, thank you for your support for this site!

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.