Created
September 18, 2015 08:46
-
-
Save invkrh/b043cfaa1906dd0165da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object LazySerializationTest extends App { | |
def serialize(obj: Any): Array[Byte] = { | |
val bytes = new ByteArrayOutputStream() | |
val out = new ObjectOutputStream(bytes) | |
out.writeObject(obj) | |
out.close() | |
bytes.toByteArray | |
} | |
def deSerialise(bytes: Array[Byte]): MyClass = { | |
new ObjectInputStream(new ByteArrayInputStream(bytes)). | |
readObject().asInstanceOf[MyClass] | |
} | |
def test(obj: MyClass): Unit = { | |
val bytes = serialize(obj) | |
val fromBytes = deSerialise(bytes) | |
println(s"Original cnt = ${obj.x.cnt}") | |
println(s"De Serialized cnt = ${fromBytes.x.cnt}") | |
} | |
object X { | |
val cnt = new AtomicInteger() | |
} | |
class X { | |
// Not Serializable | |
val cnt = X.cnt.incrementAndGet | |
println(s"Create instance of X #$cnt") | |
} | |
class MyClass extends Serializable { | |
lazy val x = new X | |
} | |
// Not initialized | |
val mc1 = new MyClass | |
test(mc1) | |
// Force lazy evaluation | |
val mc2 = new MyClass | |
mc2.x | |
test(mc2) // Failed with NotSerializableException | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment