Category: Singleton

Singleton

Singleton Invalidated by Multithreading

Singleton Invalidated by Multithreading

Singleton will work properly in multithreaded environment only if eager instantiation has been done because in this case instance creation will happen at the time of class loading only. But for Lazy instantiation we...

Singleton Invalidated by Serialization

Singleton Invalidated by Serialization

When we serialize an object and deserialize it again there are different hash code values generated as shown in the example below. So our Singleton principle breaks in case of object serialization/deserialization. Output How...

Singleton Invalidated by Clone

Singleton Invalidated by Clone

If we try to make instance by cloning it, the generated hash code of cloned copy doesn’t match with the actual object so it also violates the Singleton principle. Example Output How to fix:...

Singleton Invalidated by Reflection

Singleton Invalidated by Reflection

Using reflection we can set the private constructor to become accessible at runtime as shown in the example below. Example Output In above output we are seeing first two objects are assigned same hashcode,...

Singleton Design Pattern

Singleton Design Pattern

Sometimes it’s important for some classes to have exactly one instance. There are many objects we only need one instance of them and if we, instantiate more than one, we’ll run into all sorts...