Re: JavaMemoryModel: Object.hashCode() and System.identityHashCode()

From: Doron Rajwan (doron@rajwan.org)
Date: Sun Apr 18 2004 - 07:34:58 EDT


As I see it, all interfaces are subject to the caller
being well synchronized. Otherwise, java.util.HashMap,
w/o the synchronizedMap wrapper, is broken too.

Example:

class X {
    private int x;
    public X(int value) {
        x = value;
    }
    void setX(int value) {
        x = value;
    }
    int getX() {
        return x;
    }
    public int hashCode() {
        return x;
    }
}

I would say that this class satisfies hashCode()
contract. Is this agreed?

Now, the usage is:

Initially, obj = null.

Thread 1:
    obj = new X(3);

Thread 2:
    X obj2 = obj;
    if (obj2 != null) {
        r1 = obj2.hashCode();
        r2 = obj2.hashCode();
    }

Question: can r1 != r2 ?

YES!

However, I suggested that when removing the override
of hashCode() in X, will result the same hashCode()
value, even in this case.

Doron.

--- Jeremy Manson <jmanson@cs.umd.edu> wrote:
> >
> > Please consider adding (the default)
> Object.hashCode()
> > and System.identityHashCode() to the short list of
> > things that seems immutable to all threads, even
> in
> > case of data race:
> > 1. it is the "identity" of the object.
> > 2. without it, java.util.IdentityHashMap can be
> > broken.
> > 3. it is the last Object() method to protect.
> >
>
> From the hashCode contract:
>
> Whenever it is invoked on the same object more than
> once during an execution
> of a Java application, the hashCode method must
> consistently return the same
> integer, provided no information used in equals
> comparisons on the object is
> modified.
>
> The only way Object.hashCode() could be implemented
> legally so as not to be
> immutable is if you detect that a change has been
> made to the the object
> that can affect equals comparisons. This would be
> tough, as the equals
> comparison for Object is based on reference
> identity.
>
>
> Jeremy
> -------------------------------
> JavaMemoryModel mailing list -
http://www.cs.umd.edu/~pugh/java/memoryModel

=====
Doron Rajwan, mailto:doron@rajwan.org

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:01:05 EDT