views:

367

answers:

5

For example: Object A contains Object B that contains Object C that contains Object A.

Will Object A serialize properly?

Comment #9 here indicates that it does not work .

In contrast, XStream indicates that it does handle cyclic references.

+1  A: 

What happens when you TRY?

Jonathan Feinberg
I tried "Does java serialization work for cyclic references?" in Google about an hour ago. It appears to be working now.
Brandon
PS Wordle is cool, thanks.
Brandon
Searching on Google is not **trying**. Writing code and seeing what happens is **trying**. Thanks for the kind words on Wordle.
Jonathan Feinberg
+4  A: 

Yes, the default Java serialization works for cyclic references. When you serialize object C, the field will contain a backreference to the already-serialized object A instead of serializing it again.

Steven Schlansker
+1  A: 

Yes, Java serialization works for circular references, for read here for more information to help your understanding of what Java serialization can do.

Paul Wagland
Thanks from your link "Special cases like circular references and multiple references to a single object are preserved such that when the tree graph gets recreated new objects don't magically appear where a reference to another object in the tree should be." http://java.sun.com/developer/technicalArticles/ALT/serialization/
Brandon
A: 

You can actually view the referencing firsthand if you serialize your object to XML. The child objects are only serialized once. Any reference (anywhere in the serialized structure) to a child object that has already been serialized will simply point to that object in the file.

Serializing cyclic references can get a little messy, though, so you might want to avoid them if you can.

spork
A: 

Yes it does.

I did this very, very, simple test, and at least it finish the serialization. I assume it is correct, but you can check that with some extra lines.

import java.io.*;
class A implements Serializable { B b; }
class B implements Serializable { C c; }
class C implements Serializable { A a; }
class Test {
    public static void main( String [] args ) throws IOException {
        A a = new A();
        a.b = new B();
        a.b.c = new C();
        a.b.c.a = a;
        new ObjectOutputStream( new ByteArrayOutputStream( ) ).writeObject( a );
        System.out.println("It works");

    }    
}
OscarRyz