`
iluoxuan
  • 浏览: 570997 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

lucene的锁机制--IndexWriter

 
阅读更多

1:lucene中打开一个IndexWriter后就会把索引改lock住,如果强行在打开一个IndexWriter那么就会抛出:

Lock obtain timed out: NativeFSLock@D:\lucene\index\write.lock异常。

2:所以在Lucene中要记得及时关闭IndexWriter。

 

package com.searchtxt.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.sun.org.apache.xml.internal.security.Init;

/**
 * 测试lucene索引锁不能同时打开多个IndexWriter
 * @author lijunqing
 *
 */
public class WriteLcok {
    private Directory directory;
    private Analyzer analyzer;
    
    @Before
    public void  Init() throws IOException{
        directory = FSDirectory.open(new File("D://lucene/index"));
        analyzer = new IKAnalyzer();
    }
    
    @Test
    public void TestWriteLock() throws IOException{
        IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer );
        IndexWriter writer1 = new  IndexWriter(directory, iwc);
        //writer1.close();
        IndexWriter writer2 = null;
        try{
            if(writer1.isLocked(directory)){
                System.out.println("writer1已经被锁");
            }
            writer2 = new IndexWriter(directory, iwc);
            System.out.println("第二个IndexWriter打开成功!");
        }catch(IOException e){
            e.printStackTrace();
            System.out.println("第二个IndexWriter打开失败!");
        }finally{
            writer1.close();
        }
    }
}

 1:结果会抛出异常,

同时lucene的IndexWrite中有:

  public static boolean isLocked(Directory directory) throws IOException {
    return directory.makeLock(WRITE_LOCK_NAME).isLocked();
  }

 检查索引是否已经被锁。

而unlock方法,释放当前锁:

 public static void unlock(Directory directory) throws IOException {
    directory.makeLock(IndexWriter.WRITE_LOCK_NAME).release();
  }
 不能乱用这个。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics