my dog learned polymorphism
The moose likes Java in General and the fly likes Object reference question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Object reference question" Watch "Object reference question" New topic

Object reference question

Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
I can't seem to find a good explaination of the answer to the following question:
If two objects with non-"transient" references to each other are serialized using ObjectOutputStream, will this create an infinite loop? Explain why or why not.
I hope that someone can throw some light on this.
[ March 16, 2004: Message edited by: Nigel Browne ]
Tim West
Ranch Hand

Joined: Mar 15, 2004
Posts: 539
The short answer is "no".
I'm not sure of the serialisation algorithm details, but my understanding is that as objects are serialised, they are assigned a value (a 'serial number'), which is used by other serialised objects to reference them. Thus a circular reference in serial format is much the same as it is in the equivalent objects: there is a circular reference, but unless you try to navigate it (naively) there is no problem.
I realise this isn't the most enlightening post; perhaps one of the more experienced members can add detail.
The code below demonstrates this. I'd hoped to post the serialised object code as well, but it's pretty meaningless without both a hex viewer and a deep understanding of the serial format.

--Tim West
Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
Thanks for your reply. I had come to the same answer, but am still confused to how the locking mechanism works. All that is mentioned in the API is
Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.

I find this sentance a little hard to understand.
sopal Pal
Ranch Hand

Joined: Aug 04, 2003
Posts: 83
If you have a JDK installation and look at the file - and go to the readObject Method - with a little bit of more searching and going through the file you will be able to understand that there is a call in this method - called -
handles.markDependency(outerHandle, passHandle);
which marks the dependency and keeps it in a list and saves it so that
the parent class is not written again.

I agree. Here's the link:
subject: Object reference question
It's not a secret anymore!