use of org.apache.lucene.index.LeafReader.CoreClosedListener in project elasticsearch by elastic.
the class ShardCoreKeyMap method add.
/**
* Register a {@link LeafReader}. This is necessary so that the core cache
* key of this reader can be found later using {@link #getCoreKeysForIndex(String)}.
*/
public void add(LeafReader reader) {
final ShardId shardId = ShardUtils.extractShardId(reader);
if (shardId == null) {
throw new IllegalArgumentException("Could not extract shard id from " + reader);
}
final Object coreKey = reader.getCoreCacheKey();
if (coreKeyToShard.containsKey(coreKey)) {
// the time).
return;
}
final String index = shardId.getIndexName();
synchronized (this) {
if (coreKeyToShard.containsKey(coreKey) == false) {
Set<Object> objects = indexToCoreKey.get(index);
if (objects == null) {
objects = new HashSet<>();
indexToCoreKey.put(index, objects);
}
final boolean added = objects.add(coreKey);
assert added;
CoreClosedListener listener = ownerCoreCacheKey -> {
assert coreKey == ownerCoreCacheKey;
synchronized (ShardCoreKeyMap.this) {
coreKeyToShard.remove(ownerCoreCacheKey);
final Set<Object> coreKeys = indexToCoreKey.get(index);
final boolean removed = coreKeys.remove(coreKey);
assert removed;
if (coreKeys.isEmpty()) {
indexToCoreKey.remove(index);
}
}
};
boolean addedListener = false;
try {
reader.addCoreClosedListener(listener);
addedListener = true;
// Only add the core key to the map as a last operation so that
// if another thread sees that the core key is already in the
// map (like the check just before this synchronized block),
// then it means that the closed listener has already been
// registered.
ShardId previous = coreKeyToShard.put(coreKey, shardId);
assert previous == null;
} finally {
if (false == addedListener) {
try {
listener.onClose(coreKey);
} catch (IOException e) {
throw new RuntimeException("Blow up trying to recover from failure to add listener", e);
}
}
}
}
}
}
Aggregations