Apache Lucene open-source search software
LUCENE-4163: Improve concurrency of MMapIndexInput.clone() by using the new WeakIdentityMap on top of a ConcurrentHashMap to manage the cloned instances. WeakIdentityMap was extended to support iterating over its keys
Uwe Schindlerfcc0fea1f374
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 1f486097232..044d3758218 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -994,6 +994,11 @@ Optimizations* LUCENE-4156: DirectoryTaxonomyWriter.getSize is no longer synchronized.(Shai Erera, Sivan Yogev)+* LUCENE-4163: Improve concurrency of MMapIndexInput.clone() by using+ the new WeakIdentityMap on top of a ConcurrentHashMap to manage+ the cloned instances. WeakIdentityMap was extended to support+ iterating over its keys. (Uwe Schindler)+Bug fixes* LUCENE-2803: The FieldCache can miss values if an entry for a readerdiff --git a/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java b/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.javaindex 4d4fbf7b017..d4e39ebc195 100644--- a/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java+++ b/lucene/core/src/java/org/apache/lucene/store/MMapDirectory.java@@ -27,9 +27,7 @@ import java.nio.channels.ClosedChannelException; // javadoc @linkimport java.nio.channels.FileChannel;import java.nio.channels.FileChannel.MapMode;-import java.util.Collections;-import java.util.Set;-import java.util.WeakHashMap;+import java.util.Iterator;import java.security.AccessController;import java.security.PrivilegedExceptionAction;@@ -37,6 +35,7 @@ import java.security.PrivilegedActionException;import java.lang.reflect.Method;import org.apache.lucene.util.Constants;+import org.apache.lucene.util.WeakIdentityMap;/** File-based {@link Directory} implementation that uses* mmap for reading, and {@link@@ -261,7 +260,7 @@ public class MMapDirectory extends FSDirectory {private ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex]private boolean isClone = false;- private final Set<MMapIndexInput> clones = Collections.newSetFromMap(new WeakHashMap<MMapIndexInput,Boolean>());+ private final WeakIdentityMap<MMapIndexInput,Boolean> clones = WeakIdentityMap.newConcurrentHashMap();MMapIndexInput(String resourceDescription, RandomAccessFile raf, long offset, long length, int chunkSizePower) throws IOException {super(resourceDescription);@@ -431,9 +430,7 @@ public class MMapDirectory extends FSDirectory {}// register the new clone in our clone list to clean it up on closing:- synchronized(this.clones) {- this.clones.add(clone);- }+ this.clones.put(clone, Boolean.TRUE);return clone;}@@ -449,35 +446,25 @@ public class MMapDirectory extends FSDirectory {try {if (isClone || buffers == null) return;+ // make local copy, then un-set early+ final ByteBuffer[] bufs = buffers;+ unsetBuffers();+// for extra safety unset also all clones' buffers:- synchronized(this.clones) {- for (final MMapIndexInput clone : this.clones) {- assert clone.isClone;- clone.unsetBuffers();- }- this.clones.clear();+ for (Iterator<MMapIndexInput> it = this.clones.keyIterator(); it.hasNext();) {+ final MMapIndexInput clone = it.next();+ assert clone.isClone;+ clone.unsetBuffers();}+ this.clones.clear();- curBuf = null; curBufIndex = 0; // nuke curr pointer early- for (int bufNr = 0; bufNr < buffers.length; bufNr++) {- cleanMapping(buffers[bufNr]);+ for (final ByteBuffer b : bufs) {+ cleanMapping(b);}} finally {unsetBuffers();}}-- // make sure we have identity on equals/hashCode for WeakHashMap- @Override- public int hashCode() {- return System.identityHashCode(this);- }-- // make sure we have identity on equals/hashCode for WeakHashMap- @Override- public boolean equals(Object obj) {- return obj == this;- }}}diff --git a/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.java b/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.javaindex d381381280a..f332ef02e80 100644--- a/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.java+++ b/lucene/core/src/java/org/apache/lucene/util/WeakIdentityMap.java@@ -21,7 +21,9 @@ import java.lang.ref.Reference;import java.lang.ref.ReferenceQueue;import java.lang.ref.WeakReference;import java.util.HashMap;+import java.util.Iterator;import java.util.Map;+import java.util.NoSuchElementException;import java.util.concurrent.ConcurrentHashMap;/**@@ -38,9 +40,10 @@ import java.util.concurrent.ConcurrentHashMap;** <p>This implementation was forked from <a href="http://cxf.apache.org/">Apache CXF</a>* but modified to <b>not</b> implement the {@link java.util.Map} interface and- * without any set/iterator views on it, as those are error-prone- * and inefficient, if not implemented carefully. Lucene's implementation also- * supports {@code null} keys, but those are never weak!+ * without any set views on it, as those are error-prone and inefficient,+ * if not implemented carefully. The map only contains {@link Iterator} implementations+ * on the values and not-GCed keys. Lucene's implementation also supports {@code null}+ * keys, but those are never weak!** @lucene.internal*/@@ -97,6 +100,70 @@ public final class WeakIdentityMap<K,V> {reap();return backingStore.size();}++ /** Returns an iterator over all weak keys of this map.+ * Keys already garbage collected will not be returned.+ * This Iterator does not support removals. */+ public Iterator<K> keyIterator() {+ reap();+ final Iterator<IdentityWeakReference> iterator = backingStore.keySet().iterator();+ return new Iterator<K>() {+ // holds strong reference to next element in backing iterator:+ private Object next = null;+ // the backing iterator was already consumed:+ private boolean nextIsSet = false;++ @Override+ public boolean hasNext() {+ return nextIsSet ? true : setNext();+ }++ @Override @SuppressWarnings("unchecked")+ public K next() {+ if (nextIsSet || setNext()) {+ try {+ assert nextIsSet;+ return (K) next;+ } finally {+ // release strong reference and invalidate current value:+ nextIsSet = false;+ next = null;+ }+ }+ throw new NoSuchElementException();+ }++ @Override+ public void remove() {+ throw new UnsupportedOperationException();+ }++ private boolean setNext() {+ assert !nextIsSet;+ while (iterator.hasNext()) {+ next = iterator.next().get();+ if (next == null) {+ // already garbage collected!+ continue;+ }+ // unfold "null" special value+ if (next == NULL) {+ next = null;+ }+ return nextIsSet = true;+ }+ return false;+ }+ };+ }++ /** Returns an iterator over all values of this map.+ * This iterator may return values whose key is already+ * garbage collected while iterator is consumed. */+ public Iterator<V> valueIterator() {+ reap();+ return backingStore.values().iterator();+ }private void reap() {Reference<?> zombie;@@ -104,6 +171,9 @@ public final class WeakIdentityMap<K,V> {backingStore.remove(zombie);}}++ // we keep a hard reference to our NULL key, so map supports null keys that never get GCed:+ static final Object NULL = new Object();private static final class IdentityWeakReference extends WeakReference<Object> {private final int hash;@@ -129,9 +199,6 @@ public final class WeakIdentityMap<K,V> {}return false;}-- // we keep a hard reference to our NULL key, so map supports null keys that never get GCed:- private static final Object NULL = new Object();}}diff --git a/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.java b/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.javaindex e3a8c481170..37cc86cbc91 100644--- a/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.java+++ b/lucene/core/src/test/org/apache/lucene/util/TestWeakIdentityMap.java@@ -17,7 +17,9 @@package org.apache.lucene.util;+import java.util.Iterator;import java.util.Map;+import java.util.NoSuchElementException;import java.util.Random;import java.util.concurrent.atomic.AtomicReferenceArray;import java.util.concurrent.Executors;@@ -42,9 +44,18 @@ public class TestWeakIdentityMap extends LuceneTestCase {assertNotSame(key2, key3);assertEquals(key2, key3);+ // try null key & check its iterator also return null:+ map.put(null, "null");+ {+ Iterator<String> it = map.keyIterator();+ assertTrue(it.hasNext());+ assertNull(it.next());+ assertFalse(it.hasNext());+ assertFalse(it.hasNext());+ }+ // 2 more keys:map.put(key1, "bar1");map.put(key2, "bar2");- map.put(null, "null");assertEquals(3, map.size());@@ -84,6 +95,25 @@ public class TestWeakIdentityMap extends LuceneTestCase {map.put(key3, "bar3");assertEquals(3, map.size());+ int c = 0, keysAssigned = 0;+ for (Iterator<String> it = map.keyIterator(); it.hasNext();) {+ assertTrue(it.hasNext()); // try again, should return same result!+ final String k = it.next();+ assertTrue(k == key1 || k == key2 | k == key3);+ keysAssigned += (k == key1) ? 1 : ((k == key2) ? 2 : 4);+ c++;+ }+ assertEquals(3, c);+ assertEquals("all keys must have been seen", 1+2+4, keysAssigned);++ c = 0;+ for (Iterator<String> it = map.valueIterator(); it.hasNext();) {+ final String v = it.next();+ assertTrue(v.startsWith("bar"));+ c++;+ }+ assertEquals(3, c);+// clear strong refskey1 = key2 = key3 = null;@@ -93,7 +123,13 @@ public class TestWeakIdentityMap extends LuceneTestCase {System.runFinalization();System.gc();Thread.sleep(100L);- assertTrue(size >= map.size());+ c = 0;+ for (Iterator<String> it = map.keyIterator(); it.hasNext();) {+ assertNotNull(it.next());+ c++;+ }+ assertTrue(size >= c);+ assertTrue(c >= map.size());size = map.size();} catch (InterruptedException ie) {}@@ -101,6 +137,14 @@ public class TestWeakIdentityMap extends LuceneTestCase {assertEquals(0, map.size());assertTrue(map.isEmpty());+ Iterator<String> it = map.keyIterator();+ assertFalse(it.hasNext());+ try {+ it.next();+ fail("Should throw NoSuchElementException");+ } catch (NoSuchElementException nse) {+ }+key1 = new String("foo");key2 = new String("foo");map.put(key1, "bar1");@@ -133,7 +177,7 @@ public class TestWeakIdentityMap extends LuceneTestCase {final int count = atLeast(rnd, 10000);for (int i = 0; i < count; i++) {final int j = rnd.nextInt(keyCount);- switch (rnd.nextInt(4)) {+ switch (rnd.nextInt(5)) {case 0:map.put(keys.get(j), Integer.valueOf(j));break;@@ -150,6 +194,12 @@ public class TestWeakIdentityMap extends LuceneTestCase {// renew key, the old one will be GCed at some time:keys.set(j, new Object());break;+ case 4:+ // check iterator still working+ for (Iterator<Object> it = map.keyIterator(); it.hasNext();) {+ assertNotNull(it.next());+ }+ break;default:fail("Should not get here.");}@@ -173,7 +223,13 @@ public class TestWeakIdentityMap extends LuceneTestCase {System.runFinalization();System.gc();Thread.sleep(100L);- assertTrue(size >= map.size());+ int c = 0;+ for (Iterator<Object> it = map.keyIterator(); it.hasNext();) {+ assertNotNull(it.next());+ c++;+ }+ assertTrue(size >= c);+ assertTrue(c >= map.size());size = map.size();} catch (InterruptedException ie) {}}