---
title: "Lucene的IndexWriter初始化时的LockObtainFailedException的解决方法"
author: "zhwj184"
date: "2013-06-28T21:35:57Z"
tags: []
categories: ["开源软件"]
slug: "lucene-indexwriter-lockobtainfailedexception"
draft: false
lastmod: "2013-06-28T21:35:57Z"
id: 1896232
url: "https://zhwj184.iteye.com/blog/1896232"
---

原文链接：

[http://www.javaarch.net/jiagoushi/904.htm](http://www.javaarch.net/jiagoushi/904.htm "http://www.javaarch.net/jiagoushi/904.htm")

Lucene的IndexWriter初始化时的LockObtainFailedException的解决方法

 

本网站使用了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.&lt;init&gt;(IndexWriter.java:1098)

        at org.apache.lucene.index.IndexWriter.&lt;init&gt;(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();

}