Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a back-reference in Java?

Tags:

java

Especially in the context of readUnshared() method of ObjectInputStream, what does a "back-reference" mean?

I came across the term in this

If readUnshared is called to deserialize a back-reference (the stream representation of an object which has been written previously to the stream), an ObjectStreamException will be thrown.

Ref: https://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#readUnshared()

like image 870
user87407 Avatar asked Sep 26 '16 07:09

user87407


2 Answers

When you serialize objects using an ObjectOutputStream, the stream will 'remember' which objects it has already written. When it has to write the same object again, it will not write the whole object again, instead it will write an identifier that is called the 'back reference'.

The receiving ObjectInputStream will also keep track of what objects have been received, and will - upon reading a back reference - return the same object it read previously.

As explained in the answer by CoronA, this is - among others - used for serializing objects that point to each other, but also to ensure that identity equality in one JVM is preserved when serializing to another JVM.

The method readUnshared (and its counter part writeUnshared) are used to break away from this behavior: it ensures that the object read (written) will be unique (and not reused as a back reference). This is rather advanced and I can't remember ever having seen or having used it, but then again, I rarely see usage of serialization at all.

like image 92
Mark Rotteveel Avatar answered Oct 05 '22 09:10

Mark Rotteveel


Consider:

class A {
  B b;
}

class B {
  String s;
  A a;
}

and following construction:

A a = new A();
a.b = new B();
b.a = a;

If such a recursive structure is serialized and deserialized it should be functionally the same. b.a should not be an arbitrary instance of A but exactly the one which references b.

In this case b.a is the backreference, since A would be read before B in the ObjectInputStream.

like image 45
CoronA Avatar answered Oct 05 '22 09:10

CoronA