eclipse / eclipse-collections

Eclipse Collections is a collections framework for Java with optimized data structures and a rich, functional and fluent API.
http://www.eclipse.org/collections
2.42k stars 604 forks source link

Unexpected behaviour in updateValue() with empty key #1517

Open romanvmarkov opened 11 months ago

romanvmarkov commented 11 months ago

This issue exits in Eclipse Collections framework. Unexpected behaviour in, for instance, IntObjectHashMap.updateValue() with empty key. Apparently, the issue will be reproduced also in any PrimitiveObjectHashMap and in updateValueWith() method.

Steps to reproduce

  1. Create new IntObjectHashMap map = new IntObjectHashMap();.
  2. Update value for empty key: map.updateValue(0, () -> null, (existingValue) -> { if (map.containsKey(0)) throw new RuntimeException("key 0 does not exits at the moment"); return new Object();});
  3. Exception is thrown

Currently, map has flag containsZeroKey before the value for zero key was evaluated. It leads to true result of map.containsKey(0) call. That's quite unexpected and it's different from behaviour for non empty key. map.containsKey(0) returning false inside function expected before value for zero key was inserted to the map.

I assume, the issue will be reproduced also in any PrimitiveObjectHashMap and in updateValueWith() method. Just replacing this.sentinelValues.containsZeroKey = true; after this.sentinelValues.zeroValue = function.valueOf(factory.value()); is enough for fixing this

mohrezaei commented 11 months ago

None of the functions in any of the interfaces have been designed or tested for reentrancy. It's reasonable to expect reentrancy if the method is non-mutating, but for a mutating function, usually the point of passing in the function is late invocation, which may very well be when the collection is in a intermediate state.

mohrezaei commented 11 months ago

In a language like Rust, where the compiler enforces mutation semantics, the above code, where there is a mutable reference to the collection as well as a non-mutable reference, would immediately cause a compile error.

In Java (or any other language), if the collection is guarded by a non-reentrant lock, the above code would result in a deadlock.