Apache Solr open-source search software
LUCENE-5553: IndexReader#ReaderClosedListener is not always called on IndexReader#close()
Simon Willnauera8b93f272f7e
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex bdc8c92a376..85408c5d9e5 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -286,6 +286,12 @@ Bug Fixesindexed shapes within 1/2 maxDistErr from the edge of the query shape. This meantsearching for a point by the same point as a query rarely worked. (David Smiley)+* LUCENE-5553: IndexReader#ReaderClosedListener is not always invoked when+ IndexReader#close() is called or if refCount is 0. If an exception is+ thrown during interal close or on any of the close listerns some or all+ listerners might be missed. This can cause memory leaks if the core listeners+ are used to clear caches. (Simon Willnauer)+======================= Lucene 4.7.0 =======================New Featuresdiff --git a/lucene/core/src/java/org/apache/lucene/index/IndexReader.java b/lucene/core/src/java/org/apache/lucene/index/IndexReader.javaindex b416812fa55..cd053358d64 100644--- a/lucene/core/src/java/org/apache/lucene/index/IndexReader.java+++ b/lucene/core/src/java/org/apache/lucene/index/IndexReader.java@@ -17,6 +17,11 @@ package org.apache.lucene.index;* limitations under the License.*/+import org.apache.lucene.document.DocumentStoredFieldVisitor;+import org.apache.lucene.store.AlreadyClosedException;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.IOUtils;+import java.io.Closeable;import java.io.IOException;import java.util.Collections;@@ -25,10 +30,6 @@ import java.util.List;import java.util.Set;import java.util.WeakHashMap;import java.util.concurrent.atomic.AtomicInteger;--import org.apache.lucene.document.DocumentStoredFieldVisitor;-import org.apache.lucene.store.AlreadyClosedException;-import org.apache.lucene.util.Bits;// javadocs/** IndexReader is an abstract class, providing an interface for accessing an@@ -125,11 +126,20 @@ public abstract class IndexReader implements Closeable {parentReaders.add(reader);}- private void notifyReaderClosedListeners() {+ private void notifyReaderClosedListeners(Throwable th) {synchronized(readerClosedListeners) {for(ReaderClosedListener listener : readerClosedListeners) {- listener.onClose(this);+ try {+ listener.onClose(this);+ } catch (Throwable t) {+ if (th == null) {+ th = t;+ } else {+ th.addSuppressed(t);+ }+ }}+ IOUtils.reThrowUnchecked(th);}}@@ -225,18 +235,19 @@ public abstract class IndexReader implements Closeable {final int rc = refCount.decrementAndGet();if (rc == 0) {- boolean success = false;+ closed = true;+ Throwable throwable = null;try {doClose();- success = true;+ } catch (Throwable th) {+ throwable = th;} finally {- if (!success) {- // Put reference back on failure- refCount.incrementAndGet();+ try {+ reportCloseToParentReaders();+ } finally {+ notifyReaderClosedListeners(throwable);}}- reportCloseToParentReaders();- notifyReaderClosedListeners();} else if (rc < 0) {throw new IllegalStateException("too many decRef calls: refCount is " + rc + " after decrement");}diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java b/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.javaindex d6a67df599b..f0a584cb748 100644--- a/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentCoreReaders.java@@ -17,14 +17,6 @@ package org.apache.lucene.index;* limitations under the License.*/-import java.io.IOException;-import java.util.Collections;-import java.util.HashMap;-import java.util.LinkedHashSet;-import java.util.Map;-import java.util.Set;-import java.util.concurrent.atomic.AtomicInteger;-import org.apache.lucene.codecs.Codec;import org.apache.lucene.codecs.DocValuesProducer;import org.apache.lucene.codecs.FieldsProducer;@@ -39,6 +31,14 @@ import org.apache.lucene.store.IOContext;import org.apache.lucene.util.CloseableThreadLocal;import org.apache.lucene.util.IOUtils;+import java.io.IOException;+import java.util.Collections;+import java.util.HashMap;+import java.util.LinkedHashSet;+import java.util.Map;+import java.util.Set;+import java.util.concurrent.atomic.AtomicInteger;+/** Holds core readers that are shared (unchanged) when* SegmentReader is cloned or reopened */final class SegmentCoreReaders {@@ -166,19 +166,34 @@ final class SegmentCoreReaders {void decRef() throws IOException {if (ref.decrementAndGet() == 0) {// System.err.println("--- closing core readers");- IOUtils.close(termVectorsLocal, fieldsReaderLocal, normsLocal, fields, termVectorsReaderOrig, fieldsReaderOrig,- cfsReader, normsProducer);- notifyCoreClosedListeners();+ Throwable th = null;+ try {+ IOUtils.close(termVectorsLocal, fieldsReaderLocal, normsLocal, fields, termVectorsReaderOrig, fieldsReaderOrig,+ cfsReader, normsProducer);+ } catch (Throwable throwable) {+ th = throwable;+ } finally {+ notifyCoreClosedListeners(th);+ }}}- private void notifyCoreClosedListeners() {+ private void notifyCoreClosedListeners(Throwable th) {synchronized(coreClosedListeners) {for (CoreClosedListener listener : coreClosedListeners) {// SegmentReader uses our instance as its// coreCacheKey:- listener.onClose(this);+ try {+ listener.onClose(this);+ } catch (Throwable t) {+ if (th == null) {+ th = t;+ } else {+ th.addSuppressed(t);+ }+ }}+ IOUtils.reThrowUnchecked(th);}}diff --git a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.javaindex 907516e71a6..18a7e19a439 100644--- a/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java+++ b/lucene/core/src/java/org/apache/lucene/index/SegmentReader.java@@ -17,13 +17,6 @@ package org.apache.lucene.index;* limitations under the License.*/-import java.io.IOException;-import java.util.ArrayList;-import java.util.HashMap;-import java.util.List;-import java.util.Map;-import java.util.Map.Entry;-import org.apache.lucene.codecs.Codec;import org.apache.lucene.codecs.DocValuesFormat;import org.apache.lucene.codecs.DocValuesProducer;@@ -36,6 +29,14 @@ import org.apache.lucene.store.Directory;import org.apache.lucene.store.IOContext;import org.apache.lucene.util.Bits;import org.apache.lucene.util.CloseableThreadLocal;+import org.apache.lucene.util.IOUtils;++import java.io.IOException;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Map.Entry;/*** IndexReader implementation over a single segment.@@ -250,9 +251,11 @@ public final class SegmentReader extends AtomicReader {core.decRef();} finally {dvProducers.clear();- docValuesLocal.close();- docsWithFieldLocal.close();- segDocValues.decRef(dvGens);+ try {+ IOUtils.close(docValuesLocal, docsWithFieldLocal);+ } finally {+ segDocValues.decRef(dvGens);+ }}}diff --git a/lucene/core/src/java/org/apache/lucene/util/IOUtils.java b/lucene/core/src/java/org/apache/lucene/util/IOUtils.javaindex cfef13854c9..52cbf098d5b 100644--- a/lucene/core/src/java/org/apache/lucene/util/IOUtils.java+++ b/lucene/core/src/java/org/apache/lucene/util/IOUtils.java@@ -17,6 +17,8 @@ package org.apache.lucene.util;* limitations under the License.*/+import org.apache.lucene.store.Directory;+import java.io.BufferedReader;import java.io.Closeable;import java.io.File;@@ -30,8 +32,6 @@ import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;import java.nio.charset.CodingErrorAction;-import org.apache.lucene.store.Directory;-/** This class emulates the new Java 7 "Try-With-Resources" statement.* Remove once Lucene is on Java 7.* @lucene.internal */@@ -340,6 +340,17 @@ public final class IOUtils {if (th instanceof IOException) {throw (IOException) th;}+ reThrowUnchecked(th);+ }+ }++ /**+ * Simple utilty method that takes a previously caught+ * {@code Throwable} and rethrows it as an unchecked exception.+ * If the argument is null then this method does nothing.+ */+ public static void reThrowUnchecked(Throwable th) {+ if (th != null) {if (th instanceof RuntimeException) {throw (RuntimeException) th;}diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexReaderClose.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexReaderClose.javanew file mode 100644index 00000000000..52861d739ef--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexReaderClose.java@@ -0,0 +1,116 @@+package org.apache.lucene.index;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.analysis.MockAnalyzer;+import org.apache.lucene.store.AlreadyClosedException;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.LuceneTestCase;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.atomic.AtomicInteger;++/**+ */+public class TestIndexReaderClose extends LuceneTestCase {++ public void testCloseUnderException() throws IOException {+ final int iters = 1000 + 1 + random().nextInt(20);+ for (int j = 0; j < iters; j++) {+ Directory dir = newDirectory();+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(random(), TEST_VERSION_CURRENT, new MockAnalyzer(random())));+ writer.commit();+ writer.close();+ DirectoryReader open = DirectoryReader.open(dir);+ final boolean throwOnClose = !rarely();+ AtomicReader wrap = SlowCompositeReaderWrapper.wrap(open);+ FilterAtomicReader reader = new FilterAtomicReader(wrap) {+ @Override+ protected void doClose() throws IOException {+ super.doClose();+ if (throwOnClose) {+ throw new IllegalStateException("BOOM!");+ }+ }+ };+ List<IndexReader.ReaderClosedListener> listeners = new ArrayList<>();+ int listenerCount = random().nextInt(20);+ AtomicInteger count = new AtomicInteger();+ boolean faultySet = false;+ for (int i = 0; i < listenerCount; i++) {+ if (rarely()) {+ faultySet = true;+ reader.addReaderClosedListener(new FaultyListener());+ } else {+ count.incrementAndGet();+ reader.addReaderClosedListener(new CountListener(count));+ }+ }+ if (!faultySet && !throwOnClose) {+ reader.addReaderClosedListener(new FaultyListener());+ }+ try {+ reader.close();+ fail("expected Exception");+ } catch (IllegalStateException ex) {+ if (throwOnClose) {+ assertEquals("BOOM!", ex.getMessage());+ } else {+ assertEquals("GRRRRRRRRRRRR!", ex.getMessage());+ }+ }++ try {+ reader.fields();+ fail("we are closed");+ } catch (AlreadyClosedException ex) {+ }++ if (random().nextBoolean()) {+ reader.close(); // call it again+ }+ assertEquals(0, count.get());+ wrap.close();+ dir.close();+ }+ }++ private static final class CountListener implements IndexReader.ReaderClosedListener {+ private final AtomicInteger count;++ public CountListener(AtomicInteger count) {+ this.count = count;+ }++ @Override+ public void onClose(IndexReader reader) {+ count.decrementAndGet();+ }+ }++ private static final class FaultyListener implements IndexReader.ReaderClosedListener {++ @Override+ public void onClose(IndexReader reader) {+ throw new IllegalStateException("GRRRRRRRRRRRR!");+ }+ }++}