3

Disclaimer: this is a question meant as an intellectual exercise, hence I do not want to use Enum here.

With reference to my previous question: Java: Lazy loading Singleton and reflection attack?

Following is a solution I came up with to prevent reflection attack for IODH idiom. Could you pl. comment on the solution and suggest other approaches? (I'm aware of 'permission' approach: https://stackoverflow.com/a/8112238/266103)

Again, this code is meant strictly as an intellectual exercise, and I would never use anything like this in real life.

Also 1) this code creates two instances but retains the second if the instance is created through constructor reflection instead of calling getInstance() and, 2) it is unlikely to be thread-safe.

public class Singleton 
{
    private volatile static boolean isCreated = false;

    private static class Holder
    {
        private static Singleton instance = new Singleton();
    }

    private Singleton()
    {               
        if(isCreated)
        {
            throw new RuntimeException("Singleton Multiple Instantiation");
        }       
        Holder.instance = this;
        isCreated = true;
    }

    public static Singleton getInstance()
    {
        return Holder.instance;
    }
}
Community
  • 1
  • 1
shrini1000
  • 7,038
  • 12
  • 59
  • 99
  • - What stops attacker from setting the `isCreated` flag to false and do what ever he/she wants? - `isCreated` flag could be replaced by just `Singleton.Holder.instance != null` – Jiri Kremser Sep 18 '12 at 16:49
  • Good point about #1. Any suggestions on how to fix it? For #2, that's the first thing I tried, but then I found out that it won't work if you create the instance through constructor reflection first. – shrini1000 Sep 19 '12 at 05:12

0 Answers0