Is it safe by default, like Java's single-element-enum pattern or is it e. g. necessary to define readResolve
or similar methods somewhere to prevent accidental or malicious breakage of the singleton contract?
Prevent Singleton Pattern From Deserialization To overcome this issue, we need to override readResolve() method in the Singleton class and return the same Singleton instance.
Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.
No sir, not really the same. Singleton is a technique to make sure there's only one instance of a class, but a static class never gets instantiated - check out this (.
Advantage of Singleton design patternSaves memory because object is not created at each request. Only single instance is reused again and again.
Yes, it is safe by default:
object Singleton extends Serializable
// with Scala 2.8: @serializable object Singleton
import java.io._
val out = new ObjectOutputStream(new FileOutputStream("singleton"))
out.writeObject(Singleton)
out.close
val in = new ObjectInputStream(new FileInputStream("singleton"))
val obj = in.readObject
in.close
obj == Singleton // should print true
When you compile the object with scalac and decompile it (for example with JAD) you will get following Java-file:
public final class Singleton$ implements Serializable, ScalaObject
{
public Object readResolve()
{
return MODULE$;
}
private Singleton$()
{
}
public static final Singleton$ MODULE$ = new Singleton$1();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With