原文鏈接:
http://www.javaarch.net/jiagoushi/904.htm
本網站使用了lucene來支持搜索功能,然後定時重建索引,但是最近日誌裏面出現了下面的異常。
這個異常是因爲lucene進入到索引目錄中,發現裏面就是一個write.lock。而IndexWriter的構造函數在試圖獲取另外一個IndexWriter已經加鎖的索引目錄時就會拋出一個LockObtainFailedException。
[ERROR] 2013-06-28 14:00:01,009 [org.springweb.lucene.DataIndex.index] - DataIndex index got error Lock obtain timed out: NativeFSLo
ck@/root/data/write.lock
org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out: NativeFSLock@/root/data/write.lock
at org.apache.lucene.store.Lock.obtain(Lock.java:84)
at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:1098)
at org.apache.lucene.index.IndexWriter.<init>(IndexWriter.java:926)
at org.springweb.lucene.DataIndex.index(DataIndex.java:36)
之前的代碼是這樣的
indexwrite.commit();
indexwrite.close();
在close方法裏面也會調用unlock方法,就是刪除write.lock的鎖文件,但是之前在索引過程中拋出了異常,導致這個鎖沒有被釋放,下次再建索引的時候就拋異常了。
所以要麼在indexwrite構造方法前調用,要麼保證indexwrite.close();能被調用。
// indexwrite.getDirectory().close();
if (IndexWriter.isLocked(directory)) {
IndexWriter.unlock(directory);
}
unlock就是刪除public static final String WRITE_LOCK_NAME = "write.lock";這個文件
public static void unlock(Directory directory) throws IOException {
directory.makeLock(IndexWriter.WRITE_LOCK_NAME).release();
}