Please explain about singleton class. I know that, only on instance can be created for a singleton class. Is that correct?
Throw some light on that please......
You are right in saying that a singleton class allows only one instance of that class. But it is important to know that ONE INSTANCE PER JVM. That is to say that as long as the JVM is up and running, only one instance can be used. This is used when a Class is Behavior based rather than State based.
Thanks folks for your insights on Singleton Class. But I have a query. Shouldn't we override the clone method which every class inherits from the Object class in Java, to prevent any cloning of the object of our Singleton class.
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
Do not forget the thread safety aspect !
If you are using the previous code, in a multi-threading context, then you can create several singletons.
Which is not good !
Hi,
In Singletons also make sure that the class can not be serialized.
Once serialized another instance can very well be created.
Probably make variable " singleton " as transient to prevent it from Serializing.
OR
Do not implement java.io.Serializable.
This method will actually replace the object that was just deserialized with the return of getInstance(). The result is, ObjectInputStream's readObject() will return the singleton instance.