Singleton In Java : Break (and Secure) it.

Kiran Pande
1 min readJun 25, 2020

We have seen how to create Singleton object in Java

Purpose of Singleton is to create one and only one instance of class.

There are three techniques, by which application can break Singleton pattern. It will create more than one object of singleton class. Hashcode is used to check if there are more than one objects. If hashcode of two instance is different, then there are two different objects.

  • Reflection
  • Cloning
  • Serialisation

Reflection

Using reflection, application can call constructor directly.

Solution to Reflection.

Cloning

Using Object class method clone(), we can create clone (or different object) of same class.

Solution to cloning is to return same instance in clone() method.

Serialisation

Solution to serialisation is to return same instance in readResolve() method.

Thank You :)

--

--