15

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?

soc
  • 27,983
  • 20
  • 111
  • 215

1 Answers1

4

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();
}
kiritsuku
  • 52,967
  • 18
  • 114
  • 136
  • 1
    Why is `Singleton` not serializable by default? – soc May 15 '11 at 18:45
  • @soc - that question is no different to asking why all types aren't serializable by default - there's a Java question to that effect [here](http://stackoverflow.com/questions/441196/why-java-needs-serializable-interface). – McDowell May 15 '11 at 19:09
  • 1
    I disagree. There is basically only one (in 99,5% of the use cases) sensible implementation for serializing the singleton pattern, which is easily overridable if necessary. I just wonder if those 140 bytes saved are _that_ important that it is allowed by default to break the singleton contract. – soc May 15 '11 at 20:59