Re: [scala-bts] (SI-9375) readResolve for nested objects causes a new object to be created instead of using the de-serialized one

24 views
Skip to first unread message

Aleksandar Prokopec

unread,
Jul 20, 2015, 7:14:15 AM7/20/15
to Lukas Rytz (JIRA), aleksanda...@epfl.ch
You're right, it does not seem straightforward to avoid double ctor invocation.
Could you override readObject (or add custom code to it) to ensure that the singleton is properly initialized?

Otherwise, I guess this corner case can be ignored.

On July 20, 2015 11:38:00 AM GMT+02:00, "Lukas Rytz (JIRA)" <scala-i...@googlegroups.com> wrote:
Lukas Rytz edited a comment on Bug SI-9375
 
Re: readResolve for nested objects causes a new object to be created instead of using the de-serialized one
Thanks for you comment, Alex.

I'm not sure your suggestion would help in the situation you describe though. It seems {{readResolve}} is called only after {{readObject}} returns
 (example below) . So we'd get this sequence of events:
* start de-serializing the {{Outer}} instance
* start de-serializing the {{attr$}} instance for the {{attr$module}} field
* invoke {{attr$.readObject}}
** invokes the {{outer$.attr}} getter, which finds the {{attr$module}} field still being {{null}}, so a new module instance is created (constructor side-effects!)
* invoke {{attr$.readResolve}}
** the {{outer$.attr$module}} field is non-null, so its value is returned

I don't see a way to prevent invoking the module constructor if the module is accessed by a custom {{readObject}}.


{code}
case class C(var s: String) {
  private def readObject(in: ObjectInputStream): Unit = {
    println("Before Default")
    println(this)
    in.defaultReadObject
    println("After Default")
    println(this)
    this.s = "readObject"
    println(this)
  }

  private def readResolve(): Object = {
    println("readResolve")
    C("readResolve")
  }
}
{code}

{noformat}
scala> val c = C("orig")
c: C = C(orig)

scala> serializeDeserialize(c)
Before Default
C(null)
After Default
C(orig)
C(readObject)
readResolve
res2: C = C(readResolve)
{noformat}
Add Comment Add Comment
 
This message was sent by Atlassian JIRA (v6.4.7#64022-sha1:4cb2968)
Atlassian logo

--
Sent from my Android device with K-9 Mail. Please excuse my brevity.
Reply all
Reply to author
Forward
0 new messages