Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which guarantees do Scala's singletons have regarding serialization?

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?

like image 387
soc Avatar asked May 14 '11 20:05

soc


People also ask

How do you protect Singleton from serialization?

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.

What is use of serialization interface in Singleton design pattern?

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.

Can we serialize singleton class in C#?

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 (.

What is the advantage of Singleton design pattern?

Advantage of Singleton design patternSaves memory because object is not created at each request. Only single instance is reused again and again.


1 Answers

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();
}
like image 62
kiritsuku Avatar answered Oct 13 '22 11:10

kiritsuku