Je n'arrive pas à faire sans stop() pour un thread
Bonjour.
je travaille actuellement sur une application utilisant le moteur de recherche lucene.
Je voulais mettre au point une espéce de timeout pour interrompre les requetes qui prennent trop de temps.
Pour cela j'ai mis ma fonction qui fait la recherche dans un thread et j'interromp le thread avec la méthode stop au bout d'un certain temps si je n'ai pas eu de réponse. Cela fonctionne très bien.
Mais d'après ce que j'ai pu lire ici la méthode stop n'est pas conseillé du tout...
Mais je ne vois pas trop comment faire autrement.
Voila un extrait de mon code :
Le bean où je lance ma recherche
Code:
1 2 3 4
|
SearchThread ThSearch = new SearchThread(lQuery,lSearcher);
ThSearch.start();
Hits lHits = rechercheTimeOut(10000,ThSearch); |
la fonction rechercheTimeOut
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public Hits rechercheTimeOut(int timeur, SearchThread ThSearch) {
Hits lHits;
int TestFin = 0;
Object o=new Object();
long time = System.currentTimeMillis();
while ((time + timeur > System.currentTimeMillis() && (TestFin == 0)) ) {
try { synchronized(o) { o.wait(10); } } catch(InterruptedException ex) { }
TestFin = ThSearch.getTestFin();
}
TestFin = ThSearch.getTestFin();
if (TestFin == 0) {
lHits=null;
ThSearch.stop(); //attention : potentiellement dangereux, à voir si méthode plus élégante
}else{
lHits=ThSearch.getHits();
ThSearch.Reprendre();
}
return(lHits);
} |
Et enfin le run de mon thread :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int Attente;
public void run() {
try {
lHitsRetour=this.cherche(critere,typeTri);
TestFin=1;
while(Attente==1) sleep(1);
} catch( Exception e ) {
System.out.println("InterruptedException 1, exception du run :"+e);
}
}
public void Reprendre() {
Attente =0;
}
public int getTestFin() {
return(TestFin);
}
public Hits getHits() {
return(lHitsRetour);
} |
Je fais appel au search de lucene dans ma fonction cherche().
Aucun des deux squelettes dans la faq ne peuvent aller car en fait il n'y a que l'instruction search de lucene qui met du temps à s'executer et c'est l'execution de cette instruction que j'interromps en fait.
Si vous connaissez une meilleure solution (sans modifier le code de lucene) je suis preneur.