Re: Distinct ID Number Per Object?
On Jun 16, 4:11 pm, Lew <l...@lewscanon.nospam> wrote:
[snip]
Uh-oh. Some people are apparently on the warpath again, and I've been
attacked and accused of stuff.
Disregard all disparaging comments directed towards me. None of them
are true. They are to be ignored.
Regarding identityHashCode() -- I have it on good authority than the
Sun JVM implementation, and the typical implementation, uses the RAM
address of the object's handle (which isn't moved by compacting gc).
This address is necessarily unique for objects of overlapping
lifetime. The 32 bit code derived from it is not guaranteed unique on
a 64-bit system, but the odds of a collision are still extremely
minuscule unless the system is vastly larger than any current hardware
can cope with. (The running Java app had to occupy a gig or more with
just the objects that need unique IDs before a collision is remotely
likely.)
Of course the slight risk might still be intolerable. As with the risk
that occurs when using a JVM that may not use the RAM address, it's
probably also quite small. The RAM address of the handle is a free
collisionless hash on 32-bit architectures, and still gives a very
good hash distribution on 64-bit ones, so it is difficult to imagine
why anyone would implement a JVM to do something more complicated that
probably gives a poorer distribution of hashes and more collisions,
unless it was radically different in its guts, say not even having a
handle with a pointer to the class and a pointer to the instance, and
then it's hard to see how they could make GC work...
Regardless, the OP has since revealed that they control a base class
of the classes that need the IDs, which makes it simple to solve their
problem with zero risk of collisions. The method was also mentioned in
my earlier post, though this fact seems to have gone unacknowledged:
public class Base {
public final long id; // should stay unique even on 64-bit
architectures, or with long running systems
private static long idGenerator;
public Base () {
synchronized (Base.class) {
id = idGenerator;
idGenerator++;
}
}
...
}
If you don't construct Base instances in more than one thread at a
time, you can dump the synchronization. Otherwise it is needed to
prevent race conditions with accessing and incrementing idGenerator,
which could result in two objects getting the same id at the same
time, and the next id in sequence being skipped.