Holding threads after timeout (ThreadPoolExecutor)
Hi.
I'm trying to make sure that code won't be running longer then given
time.
This code is implemented in class MyThread and executed by Executor.
When code is executing too long, TimeoutException is thrown (see
example).
I caught it and try to run method once again.
But then RejectedExecutionException is thrown (which means thread pool
is empty).
If I wait a while before running loop once again (Thread.sleep) thread
is back in pool
and code is working properly.
What I should do to make sure that thread is back in pool and I can
use it again?
Regards
import java.util.concurrent.*;
public class MyClass {
protected static ThreadPoolExecutor executor;
public void go() throws Exception {
executor = new ThreadPoolExecutor(1, 1, 10000,
TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new
ThreadPoolExecutor.AbortPolicy());
for(int i = 0; i < 10; i++) {
Callable<Object> callable = new MyThread();
Future<Object> future = executor.submit(callable);
try {
future.get(200, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
//Thread.sleep(1000);
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
new MyClass().go();
}
class MyThread implements Callable<Object> {
public Object call() throws Exception {
Thread.sleep(1000);
return null;
}
}
}