I create a pool of threads with an Executors.newFixedThreadPool, but after a time I noticed that some of them stoped to answer (call this method below).
They was destroyed? I doing synchonization and the system continues when all threads set that finished the task, but with this, the system enter in deadlock.
They was destroyed? What can I do to prevent or handle this?
//this is the method that threads call when finish the work
synchronized void setTaskFinish(){
System.out.println(Thread.currentThread().getName() + " finishing the work.");
finishedThreads++;
System.out.println(finishedThreads +" finished the work.");
if(finishedThreads == numberThreads){
finishedThreads = 0;
this.notify();
}
}
//this is the method that creates the thread
//I dont know much about this executors yet, so I think it have errors
public void execute(int numberThreads) {
for (int i = 0; i < numberThreads; i++) {
crawlers.add(new SlaveCrawler());
}
ExecutorService threadExecutor = Executors.newFixedThreadPool(numberThreads);
for (int i = 0, n = crawlers.size(); i < n; i++) {
threadExecutor.execute((Runnable) crawlers.get(i));
}
threadExecutor.shutdown();
}
EDIT: I changed entirely my logic. I have not done much testing, but everything seems ok now. Maybe it was something wrong in my old logic.
The executor won’t destroy threads that are busy executing your tasks. If you assigned 60 tasks, and only 55 “complete” (more precisely, your
setTaskFinish()method is only invoked 55 times), it could be an exception terminating your task prematurely. Deadlock is another possibility, but not the first I would examine.What happens when your task throws an unchecked exception like
RuntimeException? Does it callsetTaskFinish()from afinallyblock? Why are you managing concurrency usingsynchronizedinstead of anAtomicInteger?