[concurrency-interest] Re: AtomicInteger and AtomicLong should implement Number

Larry Riedel larryr@saturn.sdsu.edu
12 Jan 2004 16:48:01 -0000


> [You] aren't supposed to define a compareTo that returns 0
> (equals) in different cases than when equals returns true

I would agree that I would expect them to typically be the same,
and when they are not, I find it reasonable to put what the API
documentation for compareTo() recommends: "Note: this class has
a natural ordering that is inconsistent with equals."  However
in the case of an object where the only issue is that it is not
strictly immutable, I would be inclined to go ahead and just have
((compareTo(x) == 0) <=> equals(x)), and take the risk that if 
there is an object in a hashtable and its value changes, it may
may not be findable using the same key value as before.


> > But it looks to me like things are not going that way, for example
> > it appears AtomicInteger will provide intValue(), but will not
> > provide the corresponding obvious(*) implementations of compareTo(),
> > equals(), and hashCode(), because "usages would almost never be
> > correct".  MY assumption would be that with competent software
> > engineers at the helm, which I think should be a fundamental
> > assumption behind ALL API design, usages would be as correct as they
> > are with anything else.
>
> [If I used] AtomicIntegers as keys in a hash table (HashMap,
> Hashtable, ConcurrentHashMap), I would surely want to be able to find
> them even if they changed value. Using the default identity-based
> hashCode and equals methods provides this; so normal usages would
> almost always be correct, while with value-based versions, they almost
> never would be.

I would say it would, regardless of anything to do with atomic vs not
atomic, be an inauspicious decision to use an object as a key in a
hashtable during a period of time when its value as a key might change
during the normal/expected course of events in the application.  So it
makes sense to me that the hashCode() documentation for ByteBuffer says,
"Because buffer hash codes are content-dependent, it is inadvisable to use
buffers as keys in hash maps or similar data structures unless it is known
that their contents will not change."  I like that it is left up to the
engineer/developer to be responsible for determining when it makes sense
to use an object which is not strictly immutable as a key in a hashtable.

Ruby has "rehash".  I recommend adding that. 8-)
http://www.rubycentral.com/book/ref_c_hash.html#Hash.rehash


Larry