[concurrency-interest] Minor generics nit in AtomicReferenceArray

David M. Lloyd david.lloyd at redhat.com
Thu Mar 26 21:33:23 EDT 2009

On 03/26/2009 07:57 PM, Dhanji R. Prasanna wrote:
> On Fri, Mar 27, 2009 at 9:43 AM, David M. Lloyd <david.lloyd at redhat.com 
> <mailto:david.lloyd at redhat.com>> wrote:
>     But comparisons based on object identity need not have matching
>     types.  In other words, given: "Object foo; T bar;", "foo == bar" is
>     a valid expression.
> Yea but Martin's point is that that expression will only ever be true if 
> foo and bar are of exactly the same type. Which, is not the case with 
> equals and collections, both of whom will work with covariant types.

But plain type paramters like E *are* covariant.  Any variable that holds 
an E can also hold a ? extends E.  Case in point: an 
AtomicReferenceArray<Object> can hold more than just Object instances, and 
the identity comparison will work just fine.

In any case, if you're using a AtomicReferenceArray<T>, unless you have a 
Class<? extends T> handy, you'll never be able to test that the type is 
compatible; AtomicReferenceArray on the other hand has such a mechanism 
built-in (the identity comparison).  So imagine this situation.  I'm 
implementing ConcurrentMap<K, V>.remove(Object key, Object value).  My 
AtomicReferenceArray's type parameter is V.  What can I do?  I *know* that 
the expression will only ever be true if "value" is a V, but I have no way 
to test for it.  I can cast the "value" parameter to V and suppress the 
warning, which will work (the cast is erased), but it's ugly.

It's a matter of debate whether ConcurrentMap is too lax or 
AtomicReferenceArray is too strict, but of those two choices, 
AtomicReferenceArray is the only one that can be fixed in a 
backwards-compatible fashion.  Though it's also worth noting that in 
contrast to remove(Object,Object), ConcurrentMap.replace(K key, V oldValue, 
V newValue) uses strongly typed parameters where it *could* use Object for 
"oldValue" safely.


More information about the Concurrency-interest mailing list