RFR: 7057785 : (xs) Add note to hashCode() that support for self referential is optional

Mike Duigou mike.duigou at oracle.com
Wed Aug 28 23:23:39 UTC 2013

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
   try {
       // ... the normal toString() ...
   } finally {

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.


> -- 
>  Alan Eliasen
>  eliasen at mindspring.com
>  http://futureboy.us/

More information about the core-libs-dev mailing list