...
This compliant solution obtains the return value of the task (future) and invokes the cancel()
method on it.
Code Block | ||
---|---|---|
| ||
public class PoolService { private final ExecutorService pool; public PoolService(int poolSize) { pool = Executors.newFixedThreadPool(poolSize); } public void doSomething() throws InterruptedException { ThreadFuture<?> threadfuture = new Thread(new Task())null; try { Future<?> future = pool.submit(new Task(thread)); // ... } catch(Throwable t) { future.cancel(true); // Forward to handler } } } |
Risk Assessment
Trying to force thread shutdown can result in inconsistent object state and corrupt the object. Critical resources may also leak if cleanup operations are not carried out as required.
...