Java Singleton mode

Source: Internet
Author: User
Tags volatile

Yesterday the company plans to make some of the functions of the project in the form of the SDK, for other companies to use the product, so have to re-examine the singleton mode.

Why a single case

1, in memory only one object, save memory space. Avoid frequent creation of destroyed objects, which can improve performance. Avoid multiple uses of shared resources. can be accessed globally.

2. Ensure that there is only one instance of a class, instantiate it yourself and provide this instance to the system

Problems needing attention in single case

1. Thread Safety issues

2. Use of resources

In fact, this article is talking about these two issues

1, Mode 1 (a Hungry man type)
Package Com;public class Singleton {private static Singleton instance = new Singleton ();p rivate Singleton () {}public Stati C Singleton getinstance () {  return  instance;  }  }

Pros: The instance has been created before getinstance () is called, and is inherently thread-safe

Disadvantage: If getinstance () has not been called, but an instance has been created, the resource is wasted.

2, Mode 1 (lazy type)
Package Com;public class Person {private static person person;p rivate person () {}public static person get () {if (person = = NULL) {person = new person ();} return person;}}

Advantage: The Get () method is called when the instance is created, saving resources.

Disadvantage: Thread is not secure.

This pattern can be done in singleton mode, but only in single-threaded cases, if you are working in multiple threads, multiple instances may appear.

Test: Start 20 threads, and then print the memory address of the person instance in a thread

Package Com;public class A1  {public static void main (string[] args) {for (int i = 0;  I < 20; i + +) {new Thread (new Runnable () {@Overridepublic void run () {System.out.println (Person.get (). Hashcode ())}). Start ();;}}

Result: You can see that there are two instances

Cause of the cause:

thread A wants to use Person, call the Get () method. Because it is the first call, a discovers that the person is null, and it starts to create the instance, at this time, the CPU takes time slice switch, thread B starts execution, it wants to use person, call get () method, also detects person is null--notice, This is switched after a has been detected, meaning that a does not have time to create the object-so B begins to create it. b After the creation is complete, switch to a to continue execution, because it has been detected, so a will not be detected again, it will directly create the object. In this way, threads A and B each have an object of person--a single case failure!

Summary: 1, can be implemented single-threaded single case

2, multi-line single case can not guarantee

Improvement: 1, lock

3, with synchronized plus lock synchronization
Package Com;public class Person {private static person person;p rivate person () {}public synchronized static person get () {I F (person = = null) {person = new person ();} return person;}}

 After testing, has been able to meet the security problems of multi-threaded, synchronized modified synchronization block is more than the normal code segment several times slower! If there are many calls to get (), then the performance problem has to be considered!

Advantages:

1, to meet single-threaded singleton

2, to meet the single case of multithreading

Disadvantages:

1. Poor performance

4, improve performance double check
Package Com;public class Person {private static person person;p rivate person () {}public synchronized static person get () {I F (person = = null) {synchronized (person.class) {if [person = = null] {person = new person ();}}} return person;}}

  First, the person is not NULL, if NULL, the lock is initialized, and if not NULL, the person is returned directly. The entire design, double check.

Advantages:

1, to meet single-threaded one-case

2, to meet the multi-threaded single case

3, performance problems can be optimized

Cons: Unpleasant response at first load, occasional failure due to Java memory model for some reasons

5, volatile keyword, to solve the drawbacks of double check
Package Com;public class Person {private static volatile person person = null;p rivate person () {}public static person Geti Nstance () {if (person = = null) {synchronized (Person.class) {if (person = = null) {person = new person ();}}} return person;}}

 Assuming that there is no keyword volatile, two threads A, B, are the first to call the Singleton method, thread a first executes person = new person (), the constructor is a non-atomic operation, compiled after the generation of multiple bytecode instructions, due to the Java instructions re-ordering, The assignment of a person may be performed first, which actually simply returns a reference to the memory after it has been opened in memory, and then the person is not empty, but the actual initialization operation is not executed, and if thread B enters at this point, it will see a non-empty but incomplete The person object (without completing the initialization), so you need to add the volatile keyword, prohibit the command reordering optimization, and thus secure the implementation of the Singleton.

Add: Look at the picture loading frame Glide (3.7.0 version) source code, found that Glide is also the use of volatile keyword double-check implementation of the single case, it can be seen that this method is trustworthy.

6. Static internal class
Package Com;public class Person {private person () {}private static class personholder{/** * static initializer, guaranteed thread-safe by the JVM */private St atic person instance = new person ();} public static Person getinstance () {return personholder.instance;}}

Advantages:

1, the resource utilization is high, does not execute getinstance () does not have the instance, may execute this kind of other static method

Summarize:

1, the above 6 methods, have achieved a certain degree of a single case, each has pros and cons, according to the use of different scenarios, need to meet the characteristics of different, select the appropriate single case method is the right path.

2, strict requirements for the thread, the resource requirements are not strict recommended use: 1 a hungry man type

3, the thread requirements are not strict, the resource requirements of strict recommended use: 2 lazy type

4, the thread requirements are slightly strict, the resource requirements of strict recommended use: 4 double plus lock

5, at the same time on the thread, resource requirements very strict recommended use: 5, 6

Java Singleton 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.