Getters supporting optimistic read locking (StampedLock)
frajt opened this issue · 0 comments
We are maintaining our own Trove implementation with plenty of extensions. Recently we have added a set of getter methods handling optimistic read access via the new JDK8 StampedLock. All open addressing map implementations seem to be fitting very well as there is usually just one object array read / iterated representing a table of keys. When key objects are fully immutable there is no risk of running through uncommitted memory (hashCode invocation) when the table of keys gets modified by a writer thread neither it should corrupt probing logic (removes handling, etc).
We have added three new getters to our interface
_V optimisticGet(Object key);
V optimisticGetOrDefault(Object key, V defaultValue);
boolean optimisticContainsKey(Object key);
with very simple implementations which require only extra check for the table length in a case the map/table got rehashed by a writer in between (shrink rehash).
Example
public V optimisticGet(final Object key) {
final int index = this.index((K) key);
if(index < 0) {
return null;
} else {
final V[] values = this._values;
if(index < values.length) {
return values[index];
} else {
// XXX recognized optimistic read failure
return null;
}
}
}
Obviously the StampedLock with its optimistic fragile read access is something new for us. Hope we understood it right but the proposed code should be all what the open addressing maps require to be able to handle it. Keeping in mind that our implementation is using FREE=null; (no refill after each and every allocation) and we have loop detection in the index probation loop (required when there would be no FREE entry after insertion available causing infinite loop in the optimistic access).
Michal