You do not need an ExecutorService just to start one thread at a time. You can create a FutureTask that gives you the same benefits without the overhead.
FutureTask<T> future = new FutureTask<T>(callable);
Thread thread = new Thread(future);
thread.start();
try {
future.get(120 * 1000, TimeUnit.MILLISECONDS);
} ...
Selected in the above snippet will be your task. If you have Runnable (as in the previous block of code), you can turn it into Callable via:
Callable callable = Executors.callable(runnable, null);
, , :
backgroundExecutor.execute(new Runnable() {
public void run() {
Runnable myRunnable = new Runnable() {
public void run() {
}
}
Callable callable = Executors.callable(myRunnable, null);
FutureTask<T> future = new FutureTask<T>(callable);
Thread thread = new Thread(future);
thread.start();
try {
future.get(120 * 1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.error("InterruptedException while notifyTransactionStateChangeListeners()", e);
future.cancel(true);
} catch (ExecutionException e) {
logger.error("ExecutionException", e);
} catch (TimeoutException e) {
logger.error("TimeoutException", e);
future.cancel(true);
}
}
});
, , . , , .