How to implement Singleton mode in Java

Source: Internet
Author: User
Tags volatile

In Java, a singleton pattern typically has 2 categories of a hungry man patterns and lazy patterns.

A hungry man mode refers to a singleton instance that was created when the class was loaded.

The lazy way value is that a singleton instance is created when it is first used.

Both a hungry man and lazy patterns use a static member variable to hold a real instance. and privatization of constructors to prevent external instantiation.

Singleton (a Hungry man mode) code:

public class Singleton {private final static Singleton INSTANCE = new Singleton ();    Privatization constructs a method to prevent the instantiation of private Singleton () {} public static Singleton getinstance () {return INSTANCE; }}


The singleton lazy mode code, note the static field declaration when there is a volatile keyword, and two times in the code to determine whether it is null, this dual detection mechanism in order to deal with the multi-threaded environment.

public class singleton {    private static volatile  singleton instance = null;    //privatization of construction methods to prevent instantiation      Private singleton ()  {    }    //double detection      Public static singleton getinstance ()  {        if   (Instance == null)  { //①             synchronized  (Singleton.class)  { //②                 if  (instance == null)  { //③                      instance = new singleton (); //④                 }            }         }        return INSTANCE;     }}


It is important to note that even though this doublecheck is valid in C + +, there is a bit of a problem with the code before JAVA5.

The reason is that the compiler optimizes the code and may cause the assignment statement to execute in a disorderly order, if there are 2 threads, a, B, in the above code. A thread has entered the 4 position, and when the code for 4 is executed, it is important to note that the line code INSTANCE = new Singleton () is not an atomic operation.

The JVM might first assign an uninitialized memory address to instance before completing the construction of the Singleton class, and if thread B enters the 1 position, it will assume that instance already exists, returning an uninitialized block of memory. This may cause the program to crash. It is because of the first assignment to the instance in the initialization of the memory block, or first initialize the memory block and then copied to the instance, this order is not guaranteed, so this mechanism will appear to ask. So after JAVA5, the volatile keyword is expanded to ensure that a variable write and read operation is not optimized by the compiler to chaos, and the volatile variable is not cached in the CPU register, guaranteeing its read consistency.

This has the same effect as the volatile keyword in C #.

In addition to the methods that are common in the 2 above, there are other methods. For example, the following is a more classical implementation, using an internal class, the JVM itself guarantees its own security, this pattern is also recommended in the book "Effective Java", this method is not dependent on the Java version.

public class Singleton {private Singleton () {} public static final Singleton getinstance () {return inne    Rclass.instance;    } private static class Innerclass {private static Singleton INSTANCE = new Singleton (); }}


After JAVA5, however, the simplest single implementation method is to use the enum type.

The enum keyword is new in JAVA5, which, like Class,interface, is also a data type. It can be thought of as a special class. Constructs methods, fields, methods, and so on can be implemented inside an enum, and interfaces can be implemented. There are, however, some qualifications that enumerate constructors in classes, default to private adornments, and can only use private. All instances of an enumeration class must be explicitly listed in the first row of the class, otherwise this enumeration class cannot produce an instance. The JVM guarantees that each of these enumeration values is initialized only once. Precisely because of such a feature, we can use the following code can be implemented in a single case.

public enum Singleton {INSTANCE; public void Dosth (String arg) {//Logical Code}}


In the above single example, Singleton.instance represents a single case. Very simple and efficient.

Note that the enum keyword in Java and the enum in C # are quite different and cannot be used in C #.

This article is from "a blog" blog, make sure to keep this source http://cnn237111.blog.51cto.com/2359144/1641192

How to implement Singleton mode in Java

Related Article

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.