Difficulties in Java Singleton implementation

Source: Internet
Author: User

Difficulties in Java Singleton implementation

There is a simple and efficient way to implement the singleton mode, but there is no way to ensure the integrity of Singleton under any circumstances.

Singleton mode refers to a component that is instantiated only once and used to represent the global or system scope. The Singleton mode is often used for logging, factory, window manager, and Platform Component Management. I think we should avoid the singleton mode whenever possible, because once implemented, it is difficult to change or reload, And it will cause difficulties in writing test cases and poor code structure. In addition, the singleton mode in the following article is insecure.

People spend a lot of time studying how to better implement the singleton mode, but there is a simple and efficient implementation method. However, there is no way to ensure the integrity of a single instance under any circumstances. Read the following to see if you agree.

Final Field

This method privatize the constructor and provides a public static final object:

 
  1. public class FooSingleton { 
  2.     public final static FooSingleton INSTANCE = new FooSingleton(); 
  3.     private FooSingleton() { } 
  4.     public void bar() { } 
  5. } 

When the class is loaded, the static object is initialized, and the private constructor is called for the first time and the last time. Even if multiple threads call this class before class initialization, JVM can ensure that the class is fully initialized when the thread continues to run. However, you can use the reflection and setAccessible (true) methods to create other instances:

 
  1. Constructor[] constructors = FooSingleton.class.getDeclaredConstructors(); 
  2. Constructor constructor = constructors[0]; 
  3. constructor.setAccessible(true); 
  4. FooSingleton spuriousFoo = (FooSingleton) constructor.newInstance(new Object[0]); 

We need to modify the constructor to avoid multiple calls. For example, an exception is thrown when it is called again. Modify the FooSingleton constructor as follows to prevent such attacks:

 
  1. public class FooSingleton2 { 
  2.     private static boolean INSTANCE_CREATED; 
  3.     public final static FooSingleton2 INSTANCE = new FooSingleton2(); 
  4.     private FooSingleton2() { 
  5.         if (INSTANCE_CREATED) { 
  6.             throw new IllegalStateException("You must only create one instance of this class"); 
  7.         } else { 
  8.             INSTANCE_CREATED = true; 
  9.         } 
  10.     } 
  11.     public void bar() { } 
  12. } 

This seems safer, but it is still as easy to create a new instance. We only need to modify the INSTANCE_CREATED field, and then play the same trick:

 
  1. Field f = FooSingleton2.class.getDeclaredField("INSTANCE_CREATED"); 
  2. f.setAccessible(true); 
  3. f.set(null, false); 
  4. Constructor[] constructors = FooSingleton2.class.getDeclaredConstructors(); 
  5. Constructor constructor = constructors[0]; 
  6. constructor.setAccessible(true); 
  7. FooSingleton2 spuriousFoo = (FooSingleton2) constructor.newInstance(new Object[0]); 

Any preventive measures we take may be bypassed, so this solution is not feasible.

Static Factory

Using this method, public members are similar to static factories:

 
  1. public class FooSingleton3 { 
  2.     public final static FooSingleton3 INSTANCE = new FooSingleton3(); 
  3.     private FooSingleton3() { } 
  4.     public static FooSingleton3 getInstance() { return INSTANCE; } 
  5.     public void bar() { } 
  6. } 

The getInstance () method always returns a reference to the same object. Although this solution cannot prevent reflection, it still has some advantages. For example, you can change the implementation of a singleton without changing the API. GetInstance () appears in almost all Singleton implementations, and it also indicates that this is really a singleton mode.

Delayed loading Singleton Mode

Note: in software engineering, Initialization-on-demand holder refers to the singleton mode of delayed loading. see wikipedia)

If you want to delay the creation of the singleton as much as possible, you can use the delayed initialization method. When the getInstance () method is called for the first time, the thread creates the singleton safely. This is an improvement compared to the previous scheme to create a single-instance hungry class load when this class is referenced for the first time. As follows:

 
  1. public class FooSingleton4 { 
  2.     private FooSingleton4() { 
  3.     } 
  4.     public static FooSingleton4 getInstance() { 
  5.         return FooSingleton4Holder.INSTANCE; 
  6.     } 
  7.     private static class FooSingleton4Holder { 
  8.         private static final FooSingleton4 INSTANCE = new FooSingleton4(); 
  9.     } 
  10. } 

Serialization with caution

If a singleton is serialized, it faces another threat. Therefore, you need to declare all fields as transient so that it will not be serialized) and provide a custom readResolve () method to return a reference to a unique INSTANCE.

Enumeration

Here, enumeration is used as the container for a singleton INSTANCE:

 
  1. public enum FooEnumSingleton { 
  2.     INSTANCE; 
  3.     public static FooEnumSingleton getInstance() { return INSTANCE; } 
  4.     public void bar() { } 
  5. } 

According to Java specification 8.9, "The final clone method of Enum ensures that enumeration can never be cloned, and its special serialization mechanism ensures that the object to be copied cannot be deserialized. In addition, reflection is not allowed to instantiate enumeration. This ensures that, in addition to enumeration constants, there will be no other enumeration instances of the same type ."

In this way, we seem to have easily prevented serialization, cloning, and reflection attacks. The first time I saw this passage, I immediately wanted to prove it was wrong. As shown in the following code, it is easy to bypass these protections:

 
  1. Constructor con = FooEnumSingleton.class.getDeclaredConstructors()[0]; 
  2. Method[] methods = con.getClass().getDeclaredMethods(); 
  3. for (Method method : methods) { 
  4.      if (method.getName().equals("acquireConstructorAccessor")) { 
  5.          method.setAccessible(true); 
  6.          method.invoke(con, new Object[0]); 
  7.      } 
  8.   } 
  9.   Field[] fields = con.getClass().getDeclaredFields(); 
  10.   Object ca = null; 
  11.   for (Field field : fields) { 
  12.       if (field.getName().equals("constructorAccessor")) { 
  13.           field.setAccessible(true); 
  14.           ca = field.get(con); 
  15.       } 
  16.   } 
  17.   Method method = ca.getClass().getMethod("newInstance", new Class[]{Object[].class}); 
  18.   method.setAccessible(true); 
  19.   FooEnumSingleton spuriousEnum = (FooEnumSingleton) method.invoke(ca, new Object[]{new Object[]{"SPURIOUS_INSTANCE", 1}}); 
  20.   printInfo(FooEnumSingleton.INSTANCE); 
  21.   printInfo(spuriousEnum); 
  22. } 
  23. private static void printInfo(FooEnumSingleton e) { 
  24.     System.out.println(e.getClass() + ":" + e.name() + ":" + e.ordinal()); 
  25. } 

Run this Code. The result is as follows:

Class com. blogspot. minborgsjavapot. singleton. FooEnumSingleton: INSTANCE: 0
Class com. blogspot. minborgsjavapot. singleton. FooEnumSingleton: SPURIOUS_INSTANCE: 1

The disadvantage of enumeration is that it cannot inherit from another base class because it has inherited from java. lang. Enum. To simulate this inheritance, refer to the mixed-in mode mixin pattern described in my other article ).

One advantage of enumeration is that you only need to add a new enumeration instance if you want to add "dualton in two cases" or "tringleton in three cases. For example, if you have a singleton cache, you may want to introduce multiple layers to the cache.

Conclusion

Although it is not easy to bypass Singleton protection, there is no foolproof solution. If you have a better solution, please kindly advise!

Enumeration is a simple and efficient way to implement the singleton mode. If you want to have inheritance or lazy loading, the delayed Initialization Scheme is a good choice.

Good luck to your Singleton!

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.