2

I started using AtomicReference in Java beans to have the 3state semantic when reading objects from JSON. As I like to have equals and hashCode implementations in my beans I'm wondering why AtomicReference doesn't override equals. The implementation would be trivial (simply delegate to the wrapped value).

Are there any good reasons AtomicReference doesn't override equals and hashCode?!

dpr
  • 10,591
  • 3
  • 41
  • 71
  • 1
    https://stackoverflow.com/questions/53884445/the-right-way-to-do-equals-and-hashcode-of-objects-held-by-atomicreference – Sotirios Delimanolis May 14 '20 at 17:52
  • "The implementation would be trivial" Given that this value can be changed at any time, and the value might change in between `hashCode` and `equals` evaluation: no, it's not trivial. – Andy Turner May 14 '20 at 17:52
  • 1
    @AndyTurner when taking that into account equals must not be implemented in any mutable class. – dpr May 14 '20 at 17:53
  • `hashCode()` is mainly needed for keys in a map, which doesn't make sense for atomic references. And `equals()` for the wrapped value could be an expensive operation, the object would have to be locked etc... You would probably not want to have that for atomic references. – Axel May 14 '20 at 17:54
  • @Axel It wouldn't need to be locked. An equality check is an atomic operation. – shmosel May 14 '20 at 17:58
  • @dpr I didn't say you *mustn't*, I said it wasn't trivial, and I agree it extends to mutable classes in general. I mean, yes, it's trivial to fill in the method, but the resulting behavior in things that rely on the properties of those methods is exciting. Don't we have enough sources of bugs in concurrent code to content with? :) – Andy Turner May 14 '20 at 18:00
  • @shmosel you mean testing equality using ==, right? I think OP was talking about delegating to the held objects‘ equals method. – Axel May 15 '20 at 10:10
  • @Axel The method would just check `==`. – shmosel May 15 '20 at 17:09
  • @shmosel while that would be atomic, it's not what I think about when I read "simply delegate to the wrapped value". That would rather be "simply compare the wrapped references". And that would be rather counter-intuitive, so I think it was really a good decision to leave it like it is now. – Axel May 15 '20 at 17:36

0 Answers0