Java Singleton design!

Source: Internet
Author: User

Post location Zhi: http://www.iteye.com/topic/652617

I learned the notes made by Singleton pattern and shared them with cainiao like me. Hope to help cainiao a little bit.

I have referred to: Balan's article javasingleton practical tutorial (with source code)

Address: http://balan.iteye.com/blog/164873

I. Definition

Singleton pattern: ensures that a class has only one instance and provides a global access point.

This definition contains two meanings:

First, we design a class as a separate instance managed by ourselves. At the same time, we must avoid other classes from generating instances on our own. To obtain a single instance, the singleton class is the only way.

Second, we must provide global access points for this instance: When you need an instance, you can query the instance type and it will return a single instance to you.

Note: The Singleton mode ensures that a class has only one instance, which means that only one instance can be in a specific system range. In some cases, Singleton cannot be used for singleton. If multiple Singleton objects are simultaneously loaded by different class loaders; in distributed systems such as ejbs, you should also pay attention to this situation because ejbs are cross-server and cross-JVM.

1. In a framework container: such as the Spring IoC container, You can ensure the uniqueness of the instance in the container through configuration.

2. In addition, the uniqueness of an instance can be guaranteed when a class is loaded by a single JVM or a single class loader.

If they are in two class loaders or JVM, they may have the opportunity to create their own single instance, because each class loader defines a namespace, if there are more than two class loaders, different class loaders may load the same class. From the perspective of the whole program, the same class will be loaded multiple times. If this happens in a singleton instance, multiple Singleton instances will coexist. So if your program has multiple classes loaded and you are using the singleton mode, be careful. One solution is to specify the Class Loader (specify the same class loader) for the singleton class ).

Ii. usefulness

Some objects actually only need one, such as threadpool, cache, registry, and driver of the device. In fact, the objects of these classes can only have one instance. If multiple instances are created, many problems may occur, such: abnormal Program behavior, excessive use of resources, and inconsistent results. The javasingleton mode provides us with the possibility of such implementation. Singleton also saves memory because it limits the number of instances and facilitates Java garbage collection ). We often see that the class loader in the factory mode is also implemented in the singleton mode, because the loaded class actually belongs to the resource.

Iii. Several common Java Singleton Modes

1 ). Create an instance immediately without delaying instantiation

1. Use global variables

Java code
  1. // Singleton with final field
  2. Public class Singleton {
  3. Public static final Singleton uniqueinstance = new Singleton ();
  4. Private Singleton (){
  5. }
  6. //... Remainder omitted
  7. }

In this method, the public static member is a final domain (which always contains the same object reference ). The private constructor is called only once to instantiate the public static final domain Singleton. uniqueinstace. Due to the lack of public or protected constructors, all guarantee the global uniqueness of singleton: Once the singleton class is instantiated, only one Singleton instance exists-Not many or many. Any behavior of a programmer using this Singleton class cannot be changed.

2. Use public static factory methods

Java code
  1. // Singleton with static Factory
  2. Public class Singleton {
  3. Private Static Singleton uniqueinstance = new Singleton ();
  4. Private Singleton (){
  5. }
  6. Public static Singleton getinsingleton (){
  7. Return uniqueinstance;
  8. }
  9. //... Remainder omitted
  10. }

The second method provides a public static factory method instead of a public static final domain. Using this method, we rely on JVM to immediately create a unique instance of this class when loading this class. Before JVM ensures that any thread accesses the uniqueinstance static variables, you must first create this instance.

2 ). Using delayed instantiation (using public static factory methods)

1. Non-thread-safe

Java code
  1. Public class Singleton {
  2. Private Static Singleton uniqueinstance;
  3. Private Singleton (){
  4. }
  5. Public static Singleton getinsingleton (){
  6. If (uniqueinstance = NULL ){
  7. Uniqueinstance = new Singleton ();
  8. }
  9. Return uniqueinstance;
  10. }
  11. //... Remainder omitted
  12. }

First, we use a static variable uniqueinstance to record the unique instance of the singleton class. When we want to use its instance, if it does not exist, the private constructor is used to generate a singleton class instance and assign it to the uniqueinstance static variable. If we don't need this instance, it will never be generated. This is "lazy instantiaze )". However, the preceding program cannot guarantee a single instance in a multi-threaded environment. The analysis is as follows:

Time Point Thread 1 Thread 2 Uniqueinstance Value
1 Thread 1 and 2 simultaneously access the singleton. getinstance () method    
2 Enter the singleton. getinstance () method   Null
3   Enter the singleton. getinstance () method Null
4 Execute if (uniqueinstance = NULL) Judgment   Null
5   Execute if (uniqueinstance = NULL) Judgment Null
6 Run uniqueinstance = new Singleton ()   Singleton1
7   Run uniqueinstance = new Singleton () Singleton2
8 Execute return uniqueinstance;   Singleton1
9   Execute return uniqueinstance; Singleton2

As shown in the preceding analysis, two Singleton instances have been generated.

2. Multi-thread secure

Java code
  1. Public class Singleton {
  2. Private Static Singleton uniqueinstance;
  3. Private Singleton (){
  4. }
  5. Public synchronized static Singleton getinsingleton (){
  6. If (uniqueinstance = NULL ){
  7. Uniqueinstance = new Singleton ();
  8. }
  9. Return uniqueinstance;
  10. }
  11. //... Remainder omitted
  12. }

Add the synchronized keyword to the getinstance () method, that is, lock the getinstance () method thread to force only one thread to enter this method at a time, this will solve the above multi-thread disaster. However, the locking synchronization method may cause a significant reduction in program execution efficiency. If your program has high performance requirements and your getinstance () method is frequently called, this design may not meet the program requirements. In fact, this lock synchronization method is used in this case, there are some problems, because for the singleton class, only when the getinstance () method is executed for the first time, you need to lock the method for synchronization, because once the uniqueinstance variable is set for the first time, you no longer need to synchronize this method. Every time this method is called, synchronization becomes a burden.

3. Use "double check and lock" to reduce the use of synchronization in the getinstance () method:

Java code
  1. Public class Singleton {
  2. // The volatile keyword ensures that multiple threads correctly process the uniqueinstance variable when the uniqueinstance variable is initialized to a singleton instance
  3. Private volatile static Singleton uniqueinstance;
  4. Private Singleton (){
  5. }
  6. Public static Singleton getinsingleton (){
  7. If (uniqueinstance = NULL) {// check the instance. If the instance does not exist, synchronize the code area.
  8. Synchronized (singleton. Class) {// lock it to prevent both threads from entering the synchronization code zone at the same time
  9. If (uniqueinstance = NULL) {// double check is very important. If two threads access the synchronization code area at the same time, an instance is generated after the first thread accesses the synchronization code area; when the second thread that has been waiting for the getinstance method enters the synchronization code area, a new instance is generated.
  10. Uniqueinstance = new Singleton ();
  11. }
  12. }
  13. }
  14. Return uniqueinstance;
  15. }
  16. //... Remainder omitted
  17. }

There is a deep article on double-checked locking: http://www.cs.umd.edu /~ API/Java/MemoryModel/doublecheckedlocking.html

3. Sington class serialization

To change the singleton class to serializable, it is not enough to implement the serializable interface only. To maintain Singleton, you must provide a readresolve method for the Singleton class. Otherwise, a serialized instance will generate a new instance for each deserialization. Singleton is no exception.

As follows:

Java code
  1. Import java. Io. fileinputstream;
  2. Import java. Io. fileoutputstream;
  3. Import java. Io. objectinputstream;
  4. Import java. Io. objectoutputstream;
  5. Import java. Io. objectstreamexception;
  6. Import java. Io. serializable;
  7. // Singleton with final field
  8. Public class Singleton implements serializable {
  9. Private Static final long serialversionuid = 5765648836796281035l;
  10. Public static final Singleton uniqueinstance = new Singleton ();
  11. Private Singleton (){
  12. }
  13. //... Remainder omitted
  14. Public static void main (string [] ARGs) throws exception {
  15. // Serialization
  16. Objectoutputstream = new objectoutputstream (New fileoutputstream ("D: \ singleton. OBJ "));
  17. Singleton = singleton. uniqueinstance;
  18. Objectoutputstream. writeobject (Singleton );
  19. Objectoutputstream. Close ();
  20. // Deserialization
  21. Objectinputstream = new objectinputstream (New fileinputstream ("D: \ singleton. OBJ "));
  22. Singleton singleton2 = (Singleton) objectinputstream. readobject ();
  23. Objectinputstream. Close ();
  24. // Compare the original Instance
  25. System. Out. println (Singleton = singleton2 );
  26. }
  27. }

The output result is: false.

The solution is to add readresolve () to the singleton class:

Java code
  1. // The readresolve method maintains Singleton attributes.
  2. Private object readresolve () throws objectstreamexception {
  3. Return uniqueinstance;
  4. }

Test again: the output result is true.

 

After deserialization, the newly created object will call this method first. The object reference returned by this method is returned, replacing the newly created object. Essentially, this method ignores the newly created object and returns the instance created during class initialization.

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.