Java Singleton mode, Java mode

Source: Internet
Author: User

Java Singleton mode, Java mode
Yesterday, the company planned to use some of the functions of the project in the form of sdks for the products of other companies, so we had to re-study the singleton model.

 

Why Singleton

1. There is only one object in the memory, saving the memory space. This avoids frequent creation and destruction of objects and improves performance. Avoid multiple usage of shared resources. Global access.

2. Make sure that a class has only one instance, instantiate it and provide the instance to the system.

 

Notes for Singleton

1. thread security issues

2. resource usage Problems

 

In fact, this article is discussing these two issues.

 

1. method 1 (Hunger)
package com;public class Singleton {private static Singleton instance = new Singleton() ;private Singleton(){}public static Singleton getInstance() {  return  instance ;  }  }

Advantage: The instance has been created before getInstance () is called, and the thread security is inherent.

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

2. method 1 (lazy)
package com;public class Person {private static Person person ;private Person(){}public static Person get(){if ( person == null ) {person = new Person() ;}return person ;}}

Advantage: The instance is created only when the get () method is called to save resources.

Disadvantage: The thread is not safe.

In this mode, the singleton mode can be implemented, but the singleton mode only applies to singleton processes. If you operate in multiple threads, multiple instances may exist.

Test: Start 20 threads and print the memory address of the Person instance in the 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: two instances are displayed.

Cause:

Thread A wants to use Person to call the get () method. Because it is the first call, A finds that the person is null, so it starts to create an instance, at this time, the CPU has A time slice switch, thread B starts to execute, it needs to use Person, call the get () method and detect that the person is null. Note that this is switched after detection by A. That is to say, A does not have time to create objects. Therefore, B starts to create objects. After B is created, switch to A to continue execution. Because it has been detected, A will not detect it again, and it will directly create an object. In this way, thread A and thread B each have A Person object-singleton failure!

Conclusion: 1. Single-thread Singleton can be implemented

2. Multi-line Singleton cannot be guaranteed

Improvement: 1. Lock

 

3. Use synchronized to lock Synchronization
package com;public class Person {private static Person person ;private Person(){}public synchronized static Person get(){if ( person == null ) {person = new Person() ;}return person ;}}

Tested to meet the security problem of multithreading, the synchronization block modified by synchronized is several times slower than the normal code segment! If there are many get () calls, you have to consider the performance problem!

Advantages:

1. Single-threaded Singleton

2. multi-threaded Singleton

Disadvantages:

1. Poor performance

 

4. Improved performance dual Verification
package com;public class Person {private static Person person ;private Person(){}public synchronized static Person get(){if ( person == null ) {synchronized ( Person.class ){if (person == null) { person = new Person(); } }}return person ;}}

First, judge whether the person is null. If it is null, lock initialization; if it is not null, return the person directly. Dual verification is performed throughout the design.

Advantages:

1. Single-threaded Singleton

2. multi-thread Singleton

3. Performance problems are optimized

 

Disadvantage: The first loading failed due to some java memory model reasons.

 

5. The volatile keyword solves the drawbacks of dual verification.
package com;public class Person {private static volatile Person person = null ;private Person(){}public static Person getInstance(){if ( person == null ) {synchronized ( Person.class ){if ( person == null ) {person = new Person() ;}}}return person ;}}

If there is no keyword volatile, both threads A and B call the singleton method for the first time. Thread A first executes person = new Person (), this constructor is a non-atomic operation. After compilation, multiple bytecode commands are generated. Because JAVA commands are re-ordered, the person assignment operation may be executed first, this operation actually only opens a region of the storage object in the memory and returns the reference of the memory directly. Then, the person is not blank, but the actual initialization operation has not been executed yet, if thread B enters at this time, it will see a Person object that is not empty but incomplete (Initialization is not completed). Therefore, you need to add the volatile keyword to disable command re-sorting optimization, this ensures a secure Singleton.

Supplement: I read the image loading framework Glide (version 3.7.0) source code and found that glide is also a singleton that uses the volatile keyword for dual verification. We can see that this method is trustworthy.

6. static internal class
Package com; public class Person {private Person () {} private static class PersonHolder {/*** static initializer, JVM guarantees thread security */private static Person instance = new Person ();} public static Person getInstance () {return PersonHolder. instance ;}}

Advantages:

1. If the resource utilization rate is high and getInstance () is not executed and is not instance, other static methods of this type can be executed.

 

 

Summary:

1. The methods in the above 6 have implemented a certain degree of Singleton, each of which has its own advantages and disadvantages. According to different use cases, different characteristics need to be met. The proper Singleton method is the right way.

2. Strict thread requirements and resource requirements are not strictly recommended: 1.

3. threads are not strictly required, and resource requirements are strictly recommended: 2 lazy

4. Strict thread requirements and strict resource requirements are recommended: 4 dual lock

5. Recommended for threads and resources with strict requirements: 5 and 6

 

 

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.