java-Single-Case mode

Source: Internet
Author: User

What is a singleton mode?

  The class of a singleton object must ensure that only one instance exists;

What are some aspects to be considered in a singleton model?

  Thread safety, lazy loading, serialization, and deserialization security

Several implementation methods:

The first kind: simple lazy or bad Han mode

/*** Single case mode*/ Public classSingletontest {Private StaticSingletontest singletontest =NULL; Privatesingletontest () {} Public StaticSingletontest Instance () {if(Singletontest = =NULL) {singletontest=Newsingletontest (); }        returnsingletontest; }}

The second kind: adding synchronized keyword on the method can realize thread safety, but the performance is low because the lock is added to the method;

/*** Single case mode*/ Public classSingletontest {Private StaticSingletontest singletontest =NULL; Privatesingletontest () {} Public Static synchronizedSingletontest Instance () {if(Singletontest = =NULL) {singletontest=Newsingletontest (); }        returnsingletontest; }}

The third type: double detection mechanism

Double detection mechanism, mainly in order to prevent one thread to enter the lock, another thread has gone through the Instance==null check after the problem;

/*** Single case mode*/ Public classSingletontest {Private StaticSingletontest singletontest =NULL; Privatesingletontest () {} Public StaticSingletontest Instance () {if(Singletontest = =NULL) {            synchronized(Singletontest.class) {                if(Singletontest = =NULL) {singletontest=Newsingletontest (); }            }        }        returnsingletontest; }}

Fourth type: Valatile mechanism

The first thing to understand is two points: atomic operation, command rearrangement;

1. Atomic operation (atomic) is an indivisible operation, in the computer, which means that the operation is not interrupted because of thread scheduling.

For example, a simple assignment is an atomic operation: M = 6; If the original value of M is 0, then for this operation, either the execution succeeds M becomes 6, either m or 0 is not executed, and there is no intermediate state such as m=3-even in a concurrent thread.

Declaring and assigning a value is not an atomic operation: int n = 6; For this statement, there are at least two operations:

① declaring a variable n
② assigns a value of 6 to N

--This will have an intermediate state: The variable n has been declared but has not yet been assigned a state.

-thus, in multi-threading, because of the uncertainty of the order in which threads are executed, if two threads use M, it can lead to unstable results.

2. Command rearrangement:

Command rearrangement: Java, is the JVM in order to commit the implementation of the efficiency of some optimization, that is, without affecting the results of the case, can be the execution of some statements to adjust the order;

int //  //  statement 2int//  statement 3int//  Statement 4

  normally, for sequential structures, the order of execution is from top to bottom, that is, 1234, but because of the reason for the rearrangement of instructions, because the final result is not affected, the actual order of execution may become 3124 or 1324.
since statements 3 and 4 are not atomic operations, statement 3 and statement 4 may also be split into atomic operations and then re-queued. In other words, for non-atomic operations, the split atomic operations may be rearranged in order of execution without affecting the final result.

in a single case, because Singleton = new Singleton () is not an atomic operation, it is compiled by the compiler into the following JVM directives:
A. Allocating memory space to object Singleton: Memory=allocate ();
B. Call the constructor initialization object Singleton:ctorinstance (memory);
c. Set Singleton to point to the memory space just allocated (this step is not NULL if you finish singleton);
However, due to the optimization of instruction rearrangement in the JVM, the order of execution of the second and third steps above is not fixed, so the order of final execution may be ABC or ACB. If this is the latter, then after C executes, and B does not execute, another thread 2 reads to the first singleton ==null when the Singleton is not null (but not initialized), so thread 2 returns singleton, but the singleton Direct use will be an error, that is, there is a "singleton is not null but not initialized" in the middle State;
The key here is that thread 1 writes to Singleton is not finished, and thread 2 executes the read operation;

to avoid this operation, you can use the keyword volatile keyword to achieve;
one of the functions of the volatile keyword is to prohibit the command rearrangement, to ensure that the order of the instructions executed, so that thread 2, the reference to the Singleton object either points to null, or to an initialized complete singleton, without an intermediate state;

One problem with volatile is reflection, but you can set classes as abstract classes;

/*** Single case mode*/ Public classSingletontest {Private Static volatileSingletontest singletontest =NULL; Privatesingletontest () {} Public StaticSingletontest Instance () {if(Singletontest = =NULL) {            synchronized(Singletontest.class) {                if(Singletontest = =NULL) {singletontest=Newsingletontest (); }            }        }        returnsingletontest; }}

Fifth: Effective Java recommendation, lazy loading mode for internal classes

This is a very ingenious notation:

    • For the inner class Singletonholder, it is a a hungry man-type implementation of the Singleton, when the Singletonholder initialization will be classloader to ensure synchronization, so instance is a true single case.

    • At the same time, since Singletonholder is an inner class that is only used in the getinstance () of the Singleton of the outer class, the time it is loaded is when the getinstance () method is called the first time.

    • It uses ClassLoader to ensure synchronization while allowing developers to control the timing of class loading. From the inside is a a hungry man type of singleton, but from the outside, it is really a lazy implementation.
/*** Single case mode*/ Public classSingletontest {Private Static classSingletonholder {Private Static FinalSingletontest INSTANCE =Newsingletontest (); }        Privatesingletontest () {} Public StaticSingletontest Instance () {returnsingletonholder.instance; }}

The sixth kind: Effective Java recommendation, enumeration;

Because the process of creating an enumeration instance is thread-safe, there is no synchronization of the enumeration's notation;

 Public enum singleinstance {    INSTANCE;      Public void fun1 () {         //Do  something    }}//  use  SingleInstance.INSTANCE.fun1 ();

Reference from: https://www.cnblogs.com/dongyu666/p/6971783.html

The public number: "Algorithmic enthusiasts"

java-Single-Case mode

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.