Singleton In Java : Secure It.
Singleton is part of creational design pattern. It serves to create one and only one instance of class. It is mainly used in web service call, database call. In multi-threading, if there are multiple instance of database object, then many threads can Write at same time into database. It will leave database with wrong data. So, Singleton pattern is used to avoid such scenario.
In Java, singleton is implemented using following basic rules.
- Private Static instance variable of singleton class.
- Private constructor to create object internally, but not outside of class.
- Public static getInstance() method to access private static instance.
Eager Approach
In eager approach, static instance is initialised at declaration time. This is simplest way to create singleton object as instance is created at time of class loading. But, it creates object every time even if it is not needed / used.
Static Code Block
It is same as Eager initialisation, but what if there is exception occurred while creating singleton object. To handle exception, we create singleton object in static code block.
It has same drawback as eager initialisation. Singleton object is created at early stage even though it is not needed / used. So, there is another approach of lazy initialisation.
Lazy Initialisation
In this approach, singleton object is created when it is needed. Singleton object is accessed throughout application only using static getInstance() method. so, object is created only when getInstance() method is called for first time.
getInstance() method creates singleton object for first time and returns same object each time after that. getInstance() method is synchronized for thread-safety.
Lets See How To Break (and Secure) It…
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 :)