clone() method and Singleton pattern in Java

When we are writing a class using theĀ Singleton pattern, there should be only one instance of that class at a time. We implement this by making the constructor private and adding a getInstance() method.

But what happens if we clone an instance of this class? You might think it won’t work because the constructor is private. But it works!! So we can actually make two instances of that class. Java does NOT handle this and we should do that by ourselves.

So how can we stop this? We need to override the clone() method like this,

@Override
protected Object clone() throws CloneNotSupportedException{
	throw new CloneNotSupportedException();
}

Now whenever we try to make a clone it will throw thisĀ CloneNotSupportedException.