LucenePool

packagecom.yulong.lucene.core;

importjava.io.File;

importjava.io.IOException;

importjava.util.HashMap;

importjava.util.Iterator;

importjava.util.Map;

importorg.apache.lucene.index.CorruptIndexException;

importorg.apache.lucene.index.IndexWriter;

importorg.apache.lucene.store.Directory;

importorg.apache.lucene.store.FSDirectory;

publicclassLucenePoolextendsThread{

/**

*是否执行线程方法

*/

privatebooleanisrun=true;

/**

*索引锁定池

*

*key索引路径

*valueMap<线程名词,线程状态>

*

*/

privateMap<String,Map>pool=newHashMap<String,Map>();

/**

*索引对象缓存池

*/

privateMap<String,IndexWriter>index=newHashMap<String,IndexWriter>();

/**

*得到索引读写器

*

*@paramkey索引路径

*@paramvalueMap<线程名词,线程状态>

*@return

*/

@SuppressWarnings("unchecked")

publicIndexWriterget(Stringkey,Stringthreadname){

//isrun=false;

IndexWriteriw=null;

try{

iw=getTrueIndexWriter(key);

//if(pool.containsKey(key)){

//Mapmap=pool.get(key);

//map.put(threadname,"true");

//iw=index.get(key);

//}else{//如果不存在索引读写器

//Mapmap=newHashMap();

//iw=getTrueIndexWriter(key);

//map.put(threadname,"true");

//pool.put(key,map);

//index.put(key,iw);

//}

}catch(Exceptione){

e.printStackTrace();

}

//isrun=true;

returniw;

}

/**

*通知线程处理完毕

*

*@paramkey

*@paramthreadname

*/

@SuppressWarnings("unchecked")

publicvoidover(Stringkey,Stringthreadname){

Mapmap=pool.get(key);

map.put(threadname,"false");

}

/**

*得到可写的临时文件

*

*@return

*@throwsIOException

*@throwsCorruptIndexException

*/

privateIndexWritergetTrueIndexWriter(Stringtemppath)throwsException{

IndexWriteriwriter=null;

Filefile=newFile(temppath);

if(!file.exists()){//如果文件不存在就创建

file.mkdirs();

}

//检查索引文件的文档熟路是否超过大小

Directorydirectory=FSDirectory.open(newFile(temppath));

try{

iwriter=newIndexWriter(directory,LuceneContacts.analyzer,false,newIndexWriter.MaxFieldLength(2500000));

}catch(Exceptione){

iwriter=newIndexWriter(directory,LuceneContacts.analyzer,true,newIndexWriter.MaxFieldLength(2500000));

}

returniwriter;

}

/**

*处理检测是否存在可释放的索引器

*/

@SuppressWarnings("static-access")

publicvoidrun(){

while(true){

if(isrun){//清理不可用的读写器

Stringstr="";

for(Iterator<String>it=pool.keySet().iterator();it.hasNext();){

Stringkey=it.next();

Mapmap=pool.get(key);

if(!map.containsValue("true")){

IndexWriteriw=index.get(key);

index.remove(key);

if(iw!=null){

if(str!="")

str+=",";

str+=key;

try{try{iw.close();}catch(Exceptione){}

}finally{if(iw!=null){try{iw.close();}catch(Exceptione){}}}

}

}

}

if(str!=""){

Stringtemp[]=str.split(",");

for(inti=0;i<temp.length;i++){

System.out.println("*********************************************************");

System.out.println("清理:"+temp[i]);

System.out.println("*********************************************************");

pool.remove(temp[i]);

}

}

}

try{

this.sleep(5000);

}catch(InterruptedExceptione){

e.printStackTrace();

}

}

}

}

相关推荐