Java rewrite methods and the pitfalls of initialization

Source: Internet
Author: User

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

Singleton mode refers to a class that is instantiated only once to represent a global or system-wide component. Singleton patterns are commonly used for logging, factory, window manager, and platform component management. I think to avoid using singleton mode as much as possible, because once the implementation is difficult to change or reload, but also to write test cases difficult, poor code structure and so on. In addition, the singleton pattern in the following article is not secure.

People spend a lot of time studying how to better implement a singleton pattern, but there is a simple and efficient way to implement it. However, there is no way to ensure the integrity of a singleton under any circumstances. Read below to see if you agree.

Final field

This method privatised the constructor and provides a public static final object out of the way:

 Public class Foosingleton {publicfinalstaticnew  Foosingleton (); Private Foosingleton () {}  Public void Bar () {}}

When the class loads, the static object is initialized, and the private constructor is called the first and last time. Even if there are multiple threads calling this class before the class is initialized, the JVM can guarantee that the class is fully initialized when the thread continues to run. However, using the reflection and Setaccessible (True) method, you can create additional new instances:

Constructor[] Constructors = Foosingleton. class  = constructors[0];constructor.setaccessible (true= (Foosingleton) Constructor.newinstance (new object[0]);

We need to modify the constructor so that it is exempt from multiple calls, such as throwing an exception when it is called again. You can prevent such attacks by modifying the Foosingleton constructor as follows:

 Public classFooSingleton2 {Private Static Booleaninstance_created; Public Final StaticFooSingleton2 INSTANCE =NewFooSingleton2 ();PrivateFooSingleton2 () {if(instance_created) {Throw NewIllegalStateException ("You must only create one instance of this class");} Else{instance_created=true;}} Public voidBar () {}}

This looks safer, but it's just as easy to create a new instance. We just need to modify the Instance_created field, and then play the same trick:

Field f = FooSingleton2. class. Getdeclaredfield ("instance_created"); F.setaccessible (true); F.set ( NULL false  = FooSingleton2. class  = constructors[0];constructor.setaccessible (true= (FooSingleton2) Constructor.newinstance (new object[0]);

Any precautions we take may be bypassed, so this scenario is not feasible.

Static Factory

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

 Public class FooSingleton3 {publicfinalstaticnew  FooSingleton3 (); Private FooSingleton3 () {}  Public Static return INSTANCE;}  Public void Bar () {}}

The getinstance () method always returns the same object reference. Although this scheme is not able to prevent reflection, but there are some of its advantages. For example, you can change the implementation of a singleton without changing the API. GetInstance () out of almost all of the singleton implementations, it also signifies that this is really a singleton pattern.

Lazy-loaded Singleton mode

(Translator note: In Software engineering, Initialization-on-demand holder This idiom refers to the lazy loading of the singleton mode, see Wikipedia)

If you want to delay the creation of a singleton as much as possible (lazy loading), you can use the lazy initialization method when the GetInstance () method first invokes the thread to create the singleton. Compared to the previous scenario, when the class is first referenced, a singleton (a Hungry man loading) is created, which is an improvement. As follows:

 public  class   FooSingleton4 { private   FooSingleton4 () {}  public  static   FooSingleton4 getinstance () { return   foosingleton4holder.instance;}  private  static  class   Foosingleton4holder { static  final  FooSingleton4 INSTANCE =   FooSingleton4 ();}}  

Be careful to serialize

If a singleton implements serialization, it faces another threat. It is therefore necessary to declare all the fields as transient (so that it will not be serialized) and provide a custom Readresolve () method that returns a reference to the unique instance instance.

Enumeration

Here the enumeration is used as a container for the singleton instance:

 Public enum Fooenumsingleton {INSTANCE;  Public Static return INSTANCE;}  Public void Bar () {}}

According to the Java language Specification 8.9, the final cloning method of enum guarantees that enumerations can never be cloned, and its special serialization mechanism guarantees that the copied object cannot be deserialized. Also, it is forbidden to instantiate an enumeration using reflection. These four aspects are guaranteed, and in addition to enumeration constants there will be no other homogeneous enumeration instances. ”

In this way, we seem to be simply defending against serialization, cloning, and reflection attacks. The first time I saw this, I immediately tried to prove it was wrong. Bypassing these protections is easy, as shown in the following code:

Constructor con = Fooenumsingleton.class. Getdeclaredconstructors () [0]; Method[] Methods=Con.getclass (). Getdeclaredmethods (); for(Method method:methods) {if(Method.getname (). Equals ("Acquireconstructoraccessor") {method.setaccessible (true); Method.invoke (Con,NewObject[0]);}} Field[] Fields=Con.getclass (). Getdeclaredfields (); Object CA=NULL; for(Field field:fields) {if(Field.getname (). Equals ("Constructoraccessor") {field.setaccessible (true); CA=field.get (con);}} Method Method= Ca.getclass (). GetMethod ("Newinstance",NewClass[]{object[].class}); Method.setaccessible (true); Fooenumsingleton Spuriousenum= (Fooenumsingleton) Method.invoke (CA,Newobject[]{Newobject[]{"Spurious_instance", 1}});p Rintinfo (fooenumsingleton.instance);p rintinfo (spuriousenum);}Private Static voidPrintinfo (Fooenumsingleton e) {System.out.println (E.getclass ()+ ":" + e.name () + ":" +e.ordinal ());}

Execute this code to get the result:

class com.blogspot.minborgsjavapot.singleton.fooenumsingleton:instance:0class Com.blogspot.minborgsjavapot.singleton.fooenumsingleton:spurious_instance:1

The disadvantage of an enumeration is that it cannot inherit from another base class because it has inherited from Java.lang.Enum. If you want to emulate this inheritance, you can refer to the mixed pattern (mixin pattern) described in my other article.

One advantage of enumerations is that if you later want to have "two cases (Dualton)" or "three cases (Tringleton)", you just need to add a new enumeration instance. For example, once you have a singleton cache, you might want to introduce multiple layers to the cache.

Conclusion

Although it is not easy to circumvent these protections, there is really no foolproof solution. If you have a better plan, please do not hesitate to enlighten!

Enumeration is a simple and efficient way to implement a singleton pattern. Deferred initialization is a good choice if you want to have an inherited or lazy load.

Java rewrite methods and the pitfalls of initialization

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.