How to Prevent the singleton mode from being reflected by JAVA

Source: Internet
Author: User

How to Prevent the singleton mode from being reflected by JAVA

I believe everyone knows the singleton mode. There are not a few people who have used it. I wrote a blog post titled IMPLEMENTATION OF THE singleton mode of four kinds of thread security (see: http://blog.csdn.net/u013256816/article/details/50427061), talking about the four writing methods of the singleton mode, it is also pointed out that the placeholder mode is relatively OK. For details, see the following:

package com.effective.singleton;public class Elvis{    private static boolean flag = false;    private Elvis(){    }    private  static class SingletonHolder{        private static final Elvis INSTANCE = new Elvis();    }    public static Elvis getInstance()    {        return SingletonHolder.INSTANCE;    }    public void doSomethingElse()    {    }}
However, this is based on a condition that the private constructor is not called through the reflection mechanism.
Here is an example of using the JAVA reflection mechanism to "attack" The Singleton mode:
package com.effective.singleton;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public class ElvisReflectAttack{    public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException    {        Class  classType = Elvis.class;        Constructor  c = classType.getDeclaredConstructor(null);        c.setAccessible(true);        Elvis e1 = (Elvis)c.newInstance();        Elvis e2 = Elvis.getInstance();        System.out.println(e1==e2);    }}
Running result: false
We can see that the constructor can be obtained through reflection and setAccessible (true) can be called to call the private constructor. All e1 and e2 are two different objects.
To defend against such attacks, you can modify the constructor so that it throws an exception when required to create a second instance.
After modification:
Package com. valid tive. singleton; public class ElvisModified {private static boolean flag = false; private ElvisModified () {synchronized (ElvisModified. class) {if (flag = false) {flag =! Flag;} else {throw new RuntimeException ("Singleton mode is violated! ") ;}} Private static class SingletonHolder {private static final ElvisModified INSTANCE = new ElvisModified ();} public static ElvisModified getInstance () {return SingletonHolder. INSTANCE;} public void doSomethingElse (){}}
Test code:
package com.effective.singleton;import java.lang.reflect.Constructor;public class ElvisModifiedReflectAttack{    public static void main(String[] args)    {        try        {            Class
 
   classType = ElvisModified.class;            Constructor
  
    c = classType.getDeclaredConstructor(null);            c.setAccessible(true);            ElvisModified e1 = (ElvisModified)c.newInstance();            ElvisModified e2 = ElvisModified.getInstance();            System.out.println(e1==e2);        }        catch (Exception e)        {            e.printStackTrace();        }    }}
  
 
Running result:
Exception in thread "main" java. lang. exceptionInInitializerError at com. valid tive. singleton. elvisModified. getInstance (ElvisModified. java: 27) at com. valid tive. singleton. elvisModifiedReflectAttack. main (ElvisModifiedReflectAttack. java: 17) Caused by: java. lang. runtimeException: The Singleton mode is violated! At com. Alibaba tive. singleton. ElvisModified.
 
  
(ElvisModified. java: 16) at com. Alibaba tive. singleton. ElvisModified.
  
   
(ElvisModified. java: 7) at com. Alibaba tive. singleton. ElvisModified $ SingletonHolder.
   
    
(ElvisModified. java: 22)... 2 more
   
  
 
We can see that the singleton mode is successfully blocked.
Since JDK1.5, there is still a new way to implement Singleton. You only need to write an enumeration type that contains a single element. Recommended Syntax:
package com.effective.singleton;public enum SingletonClass{    INSTANCE;    public void test()    {        System.out.println("The Test!");    }}
Test code:
package com.effective;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import com.effective.singleton.SingletonClass;public class TestMain{    public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException    {        Class
 
   classType = SingletonClass.class;        Constructor
  
    c = (Constructor
   
    ) classType.getDeclaredConstructor();        c.setAccessible(true);        c.newInstance();    }}
   
  
 
Running result:
Exception in thread "main" java.lang.NoSuchMethodException: com.effective.singleton.SingletonClass.
 
  ()    at java.lang.Class.getConstructor0(Unknown Source)    at java.lang.Class.getDeclaredConstructor(Unknown Source)    at com.effective.TestMain.main(TestMain.java:22)
 
This can also prevent the singleton mode from being "attacked ".
This writing method can also prevent serialization from damaging the singleton mode. For more information about serialization and destruction of Singleton mode, see JAVA serialization.
The enumeration type of a single element has become the best way to implement the 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.