diff lucene/src/luan/modules/lucene/LuceneIndex.java @ 521:8a217fe5b4f3

cleaner LuanState.onClose()
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 27 May 2015 03:12:28 -0600
parents dae264ad6a7b
children 70bda9184158
line wrap: on
line diff
--- a/lucene/src/luan/modules/lucene/LuceneIndex.java	Wed May 27 01:30:25 2015 -0600
+++ b/lucene/src/luan/modules/lucene/LuceneIndex.java	Wed May 27 03:12:28 2015 -0600
@@ -31,9 +31,13 @@
 import luan.LuanFunction;
 import luan.LuanJavaFunction;
 import luan.LuanException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 public final class LuceneIndex {
+	private static final Logger logger = LoggerFactory.getLogger(LuceneIndex.class);
+
 	private static final String FLD_NEXT_ID = "nextId";
 
 	final Lock writeLock = new ReentrantLock();
@@ -43,6 +47,7 @@
 	private DirectoryReader reader;
 	private LuceneSearcher searcher;
 	public final FieldTable fields = new FieldTable();
+	private boolean isClosed = false;
 
 	public LuceneIndex(LuanState luan,String indexDirStr) throws LuanException, IOException {
 		File indexDir = new File(indexDirStr);
@@ -56,6 +61,13 @@
 		writer = new IndexWriter(dir,conf);
 		writer.commit();  // commit index creation
 		reader = DirectoryReader.open(dir);
+		luan.onClose(new Runnable(){public void run() {
+			try {
+				close();
+			} catch(IOException e) {
+				logger.error("",e);
+			}
+		}});
 		searcher = new LuceneSearcher(this,reader);
 		initId(luan);
 	}
@@ -187,8 +199,19 @@
 	}
 
 	public void close() throws IOException {
-		writer.close();
-		reader.close();
+		if( !isClosed ) {
+			writer.close();
+			reader.close();
+			isClosed = true;
+		}
+	}
+
+	protected void finalize() throws Throwable {
+		if( !isClosed ) {
+			logger.error("not closed");
+			close();
+		}
+		super.finalize();
 	}