Is there a way with concurrency, that a same Object.equals(Object) returns
false?
That's something that pestered my mind one of this days, so I am looking
for a concrete answer.
(please, bear with me, I am not looking to make a beautiful code. Au
contraire, I'm lookng for a problem with code that smell)
Imagine we have a stateful Object comming from class Foo
public class Foo {
public int attribute = 0;
// hashCode implemented :P
@Override
public boolean equals(Object o) {
if (o instanceof Foo) {
Foo that = (Foo) o;
return this.attribute == that.attribute;
}
return false;
}
}
And we have some workers on Foo
public class DoomBringer implements Runnable {
private final Foo foo;
public DoomBringer(Foo foo) {
this.foo = foo;
}
@Override
public void run() {
this.foo.attribute++;
}
}
And another one that only prints the result of #equals for the object
passed as parameter to its constructor.
public class SelfEqualityTestPrinter implements Runnable {
private final Foo foo;
public SelfEqualityTestPrinter(Foo foo) {
this.foo = foo;
}
@Override
public void run() {
System.out.println(foo.equals(foo));
}
}
Is it possible that false will be printed one day if we have concurrent
threads modifying the same Foo instance?
My guess is that it's possible. I don't think equals is synchronized
unless we make it so. A way to avoid this would be testing this == o at
the Object#equals(Object o) method, but the same problem may rise from
comparing different instances that should be equal.
No comments:
Post a Comment