lucene的锁机制--IndexWriter

11 篇文章 0 订阅

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();
  }
 不能乱用这个。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值