On Aug 28 2013, at 15:54 , Alan Eliasen wrote:
> On 08/28/2013 04:47 PM, Guy Steele wrote:
>> <oldfogey> *ahem* Y'know, Common Lisp had a good solution for
>> printing self-referential structures (by a user-extensible print
>> function) back in 1984.
>>
>> It leaned on the solution that had been provided in Interlisp in
>> 1974. On a machine with one megabyte of main memory and a speed of 1
>> MIPS.
>>
>> This is not rocket science. </oldfogey>
>
> Hehe. So could you please describe the solution?
I am unsure what solution was used in Common Lisp (I think I knew once). The
most likely solution for Java Collections would be to use a
ThreadLocal<Boolean> which potentially recursive methods could check/set on
entry and avoid recursing. Explicitly concurrent hostile implementations could
use a plain boolean field rather than a ThreadLocal.
So toString() becomes:
public String toString() {
if(recursed.get()) {
return "<<this>>"; // self-referential
}
recursed(true);
try {
// ... the normal toString() ...
} finally {
recursed.set(true);
}
}
For performance and footprints reasons the Java Collections chose not to do
something like this. Graph preserving operations like serialization will
generally use a hash table with objects added by identity as keys to the table
before they are traversed. Any objects re-encountered during traversal will be
not-retraversed and are replaced in the stream with their identity.
Mike
>
> --
> Alan Eliasen
> [email protected]
> http://futureboy.us/