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;
}
}
}
Zig - 13 Oct 2007 21:16 GMT
> Hi.
>
[quoted text clipped - 13 lines]
> What I should do to make sure that thread is back in pool and I can
> use it again?
A) Use
future.cancel(true);
in your catch clause. This should request that the task be cancelled,
though there is no guarantee that the background thread will resume
picking elements out of the queue immediately.
B) The ThreadPoolExecutor constructors are available for very special
purpose crafting. Most of the time, you would want to use the Executors
class to create the pool for you. eg:
final ExecutorService executor=Executers.newSingleThreadExecutor();
try {
(your code here)
} finally {
executor.shutDown();
}
That should setup the constructor such that when you submit a task, it
will be queued until the background task has either finished it's current
task, or becomes aware that the background task was cancelled and discards
it.
HTH,
-Zig
pksiazek - 15 Oct 2007 15:41 GMT
> B) The ThreadPoolExecutor constructors are available for very special
> purpose crafting. Most of the time, you would want to use the Executors
[quoted text clipped - 7 lines]
>
> }
This is exectly what I was looking for.
Thanks a lot.
Regards