Hungry Chinese style ( recommend )

package concurencyv2.chapter1;
public class SingletonV2 {
private static final SingletonV2 instance = new SingletonV2(); private SingletonV2() {} public static SingletonV2 getInstance() {
return instance;
}
}

advantage : Preliminary static instance To create a . If we were Singleton Class to write a static method without creating an instance , It still creates an instance early . And reduce memory usage .

shortcoming : No, lazy loading The effect of , So as to reduce the utilization of memory .

Single thread

package concurencyv2.chapter1;
public class SingletonV1 {
private static SingletonV1 instance = null; private SingletonV1() {} public SingletonV1 getInstance() {
if(null == instance)
instance = new SingletonV1();
return SingletonV1.instance;
}
}

annotation : Singleton Static properties of instance in , Only instance by null Create an instance only when you're finished , Constructor private , Make sure that only one... Is created at a time , Avoid creating repeatedly .

shortcoming :4 It only works normally with a single thread , In the case of multithreading , There will be problems . for example : When two threads run at the same time to judge instance Whether it is empty if sentence , also instance It's not really a good time to create , Then both threads will create an instance .

Slacker type

package concurencyv2.chapter1;
public class SingletonV3 {
private SingletonV3() {
} private static SingletonV3 instance; public synchronized static SingletonV3 getInstance() {
if(null == instance)
instance = new SingletonV3();
return SingletonV3.instance;
}
}

annotation : On the basis of single thread, the synchronization lock is added , So that in the case of multithreading can be used . for example : When two threads want to create an instance at the same time , Because only one thread can get synchronization lock at a time , When the first thread is locked , The second thread can only wait . The first thread found that the instance was not created , Created by . The first thread releases the synchronization lock , Only the second thread can add the synchronization lock , Execute the following code . Because the first thread has created an instance , So the second thread doesn't need to create an instance . Ensure that there is only one instance in a multithreaded environment .

shortcoming : Each time through getInstance Method to get singleton There is a process of trying to get the synchronization lock in the instance . And as we all know , Locking is time consuming . Avoid if you can .

double check

package concurencyv2.chapter1;
public class SingletonV4 {
private SingletonV4() { } private static SingletonV4 instance; public static SingletonV4 getInstance() {
if(null == instance) {
synchronized (SingletonV4.class) {
if(null == instance)
instance = new SingletonV4();
}
}
return SingletonV4.instance;
}
}

annotation : Only when instance by null when , Need to get synchronization lock , Create an instance . When an instance is created , There is no need to try to lock .

shortcoming : A null pointer exception may occur , A thread gets the synchronization lock , And created , But initialization is not complete yet . Another thread directly getInstace, So the object that this thread might get , There are places where initialization is not complete , Causes null pointer of reference .

double check and add volatile ( recommend )

package concurencyv2.chapter1;
public class SingletonV5 {
private SingletonV5() { } private static volatile SingletonV5 instance; public static SingletonV5 getInstance() {
if(null == instance) {
synchronized (SingletonV5.class) {
if(null == instance)
instance = new SingletonV5();
}
}
return SingletonV5.instance;
}
}

advantage : stay instance To add the volatile, Make sure that the write operation has been completed every time the read operation is executed .

Static inner class ( recommend )

package concurencyv2.chapter1;
public class SingletonV6 {
private SingletonV6() {}
private static class SingletonHolder {
public static final SingletonV6 instance = new SingletonV6();
} public SingletonV6 getInstance() {
return SingletonHolder.instance;
}
}

enumeration enum

package concurencyv2.chapter1;
public class SingletonV7 {
private SingletonV7() {
} private enum Singleton {
SINGLETON;
private SingletonV7 instance; Singleton() {
instance = new SingletonV7();
}
} public static SingletonV7 getInstance() {
return Singleton.SINGLETON.instance;
}
}

utilize enum Features that are initialized only once , Guaranteed thread security .

Quickly understand Java More articles on the seven singleton patterns in

  1. Quickly understand Java Five singleton patterns in

    Solution 1 : Only suitable for single threaded environment ( Not good. ) package test; /** * @author xiaoping * */ public class Singleton { private static S ...

  2. Quickly understand Java Five singleton patterns in ( turn )

    Solution 1 : Only suitable for single threaded environment ( Not good. ) package test; /** * @author xiaoping * */ public class Singleton { private static S ...

  3. Java Five singleton implementation methods in

    [ Code ] Java Five singleton implementation methods in   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 2 ...

  4. java Several singleton patterns in

    At present, the more common ones are 4 Kind of (DCL For the thread safe version of lazy mode ). The implementation of singleton mode generally needs to meet the following conditions : 1. The constructor is privatized , Privatization of instance properties . 2. The initialization of the instance must only be done inside the class . 3. Provide common static methods , ...

  5. 5000 word | 24 This picture will give you a thorough understanding of Java Medium 21 Seed lock

    The main content of this article is as follows : This article has included my Java Online document . Github my SpringCloud The actual combat projects are constantly updated To help you summarize the good locks : Serial number Lock name application 1 Optimism lock CAS 2 Pessimistic locking synch ...

  6. Java Five singleton patterns in

    Java Singleton mode of mode : The singleton pattern ensures that there is only one instance of a class , Provide this instance by yourself and provide this instance to the whole system . characteristic : 1, A class can only have one instance 2 Create this instance yourself 3 The whole system uses this example example : Hereunder ...

  7. JDK Study --- In depth understanding of java Medium HashMap、HashSet Underlying implementation

    Resources for this article : 1.< Big talk data structure > 2.http://www.cnblogs.com/dassmeta/p/5338955.html 3.http://www.cnblogs.com/d ...

  8. understand Java Weak quotation in (Weak Reference)

    This article attempts to start from What.Why.How From these three perspectives Java Weak quotation in , understand Java The definition of weak reference in . Basic use scenarios and methods . Due to limited personal level , There are inevitably inaccuracies or ambiguity in the narration , I hope you can point out , ...

  9. JAVA Basic learning is throws and throw The difference between 、Java Four permissions in 、 The use of multithreading, etc (2)

    1.throws and throw The difference between throws Used outside functions , Is an exception at compile time ,throw Use in functions , It's a runtime exception Usage method public int method(int[] arr) throws ...

Random recommendation

  1. 2 DelayInterval Delay time interval class ——Live555 Source code reading ( One ) Basic component classes

    This is a Live555 The first part of the source code reading , Including time , Delay queue class , Handler description class , Hash table class these four big classes . Here is the second part of the time related class . This article is written by the mob lym fabricate , Welcome to reprint http://www.cnb ...

  2. Ajax-jQuery Realization

    load Method : Yes, in the last article javascript Native implementation ( The data format is html), use jqury Of post Methods to transform :   In the following sentence “h2 a”, The selection of returned content is realized :  $.get()\$.post ...

  3. [ Roof placement ] linux Unzip installation

    1: download mysql Unzip version package to the official website to download www.mysq.com download . download linux Just the general version 2. Basic configuration First , We are ready to Linux Environmental Science , We use CentOS 5.8 Carry out the test installation . First step , We need to ...

  4. Mysql Learning notes ( Two ) data type Add

    original text :Mysql Learning notes ( Two ) data type Add PS: Simply add the data type in String Type and column type ... Learning content : 1.String type 2. Column type storage requirements String type : i.char And ...

  5. Linux often use life Make

    One : Shutdown command 1:shutdown language Law :shutdown [-efFhknr][-t Number of seconds ][ Time ][ Warning message ] explain :shutdown Command to close all programs , And according to the needs of users , To restart or shut down the machine ...

  6. C++ Primer Feeling ( exception handling )( Four )

    When looking at the declaration of a normal function , It's impossible to know what exception the function will throw , But when you catch an exception, you need to know what kind of exception a function will throw , In order to catch the exception . Exception description : Appoint , If the function throws an exception , The exception thrown will be one of those included in the description , or ...

  7. java Commonly used tools (jps etc. ) explain

    Java It provides us with a lot of tools to help us develop , be located jdk In the catalog bin Directory , This blog will update the instructions of related tools at any time . jps Get the current running java application lgj@lgj-Lenovo-G470:~ ...

  8. Codeforces 837E Vasya&#39;s Function - number theory

    Vasya is studying number theory. He has denoted a function f(a, b) such that: f(a, 0) = 0; f(a, b) = ...

  9. EMbedding

    FNN Model : Non end to end Input --> features onehot --->FM Model ---> Output each feature weight and factor value   ----> Input neural network   ----> Output each prediction This is one ...

  10. What is meant by BLDC The motor ?BLDC How the motor rotates ?

    What is meant by BLDC The motor ?BLDC How the motor rotates ?