List<Runnable> returned from shutdownNow() can not be converted to submitted Runnable

两盒软妹~` 提交于 2019-12-07 12:00:54

问题


Below is the source code of the class.

I wanted to verify how does shutdownNow() works for not submitted task. Problem I am getting in below code is shutdownNow() return List<FutureTask> and not List<Runnable> which I have submitted List<Runnable> containing submitted instance of PrimeProducer .

In Below program I wanted to get the tasks which where not executed and their state so that I can reschedule them later. name() represents just state that I want to store.

So I am not able to convert to submitted Task.

class PrimeProducer implements Runnable {
private final SynchronousQueue<BigInteger> queue;

PrimeProducer(SynchronousQueue<BigInteger> queue) {
    this.queue = queue;
}

public void run() {
    try {
        BigInteger p = BigInteger.ONE;
        queue.put(p = p.nextProbablePrime());
    } catch (InterruptedException consumed) {
        System.out.println("Safe Exit");
        Thread.currentThread().interrupt();
    }

}

public String name() {
    return "PrimeProducer";
}

public static void main(String[] args) throws InterruptedException,
        ExecutionException {
    PrimeProducer primeProducer = new PrimeProducer(
            new SynchronousQueue<BigInteger>());//SynchronousQueue just to ensure it put is blocking
    ExecutorService executorService = Executors.newFixedThreadPool(1);
    executorService.submit(primeProducer);
    executorService.submit(primeProducer);
    List<Runnable> list = executorService.shutdownNow();
    //PrimeProducer producer = (PrimeProducer) list.get(0);// Class Cast
                                                            // Exception
    FutureTask<PrimeProducer> futureTask = (FutureTask<PrimeProducer>) list
            .get(0);
            System.out.println(futureTask.isDone());//Prints false
    futureTask.get().name();//futureTask-->PrimeProducer get() hangs.


}
}

Problematic Lines

//PrimeProducer producer = (PrimeProducer) list.get(0);// Class Cast
                                                            // Exception
 FutureTask<PrimeProducer> futureTask = (FutureTask<PrimeProducer>) list
            .get(0);
 futureTask.get().name();//futureTask-->PrimeProducer get() hangs.

回答1:


Try "execute" instead of "submit".




回答2:


This behavior happens because there is difference between how execute and submit handles task that are submitted.

execute method directly uses Runnable command which is passed to it where as submit create RunnableFuture and call execute

 RunnableFuture<Object> ftask = newTaskFor(task, null);


来源:https://stackoverflow.com/questions/12493449/listrunnable-returned-from-shutdownnow-can-not-be-converted-to-submitted-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!