(Added classpath list to CCs. This came from a thread on
netscape.public.mozilla.java about the added storage required in every
object for System.identityHashCode()).

Stuart Ballard wrote:
> 
> The only alternative is to dynamically allocate extra storage for it
> when it is first looked up... which adds a whole lot of complexity (I'll
> leave the details as an exercise for the reader, but there are a nice
> lot of them).

Replying to my own message... I've just been thinking about this a bit.
Assuming that the identity hash code isn't used often (probably a safe
assumption) why not have a list of identity hash codes and (weak)
references to the objects they refer to? These would be created on
demand and (by virtue of the weak references thingy) deleted on garbage
collection. The relocation of these references would be handled by the
garbage collector just like other references to objects. This could even
be done in pure java using 1.2's java.lang.ref package. An example of
the basic algorithm (not using weak refs) would be:

public class System {

  // Set up a linked list of entries
  private class HCEntry {
    Object obj;
    int hash;
    HCEntry next = null;
  }
  HCEntry idHashCodes = null;

  public int identityHashCode(Object o) {

    // Loop through the HCEntries in the list
    HCEntry e = idHashCodes;
    while (e != null) {
      if (e.obj == o) {

        // For super-efficiency, maybe move this entry to the top of the
chain.
        return e.hash;

      } else if (e.obj == null) {
        // Assume this happens if e.obj gets garbage collected
        // In real life e.obj would be a java.lang.Ref.weak and this
would be feasible
        // So here we would remove the entry from the chain.
      }
    }
    // If we reach here without returning, the object wasn't in the
list.
    HCEntry newHC = new HCEntry();
    newHC.obj = o;
    newHC.hash = new java.util.Random().nextInt();
    newHC.next = idHashCodes;
    idHashCodes = newHC;
  }
}

If it's really true that there's NO extra space cost in having the
identity hash code in the object header, then this isn't worth it. But
otherwise it's definitely worth considering. It reduces the overhead for
a very frequent operation (allocating objects) at the expense of an
infrequent one (the identity hash code). It also moves one more
operation out of the VM and into the class libraries, making it
portable.

Note that NSA does not actually call System.identityHashCode() very
often, just once per object (it is then cached on the java side). This
is probably a live-withable overhead considering that the vast majority
of objects in any system don't have native state, AND that on most VMs,
this bit of NSA will be overridden by having extra storage in the object
anyway.

Stuart.

Reply via email to