Unable to get CallableThread in RejectionHandler

本秂侑毒 提交于 2019-11-28 14:33:19

In your code

workers[i] = new CallableWorkerThread(random.nextInt(100));
FutureTask<Integer> task = new FutureTask<Integer>(workers[i]);
executor.submit(task);

you create a FutureTask which wraps the CallableWorkerThread instance but then you are using submit which accepts an arbitrary Runnable and returns a FutureTask which wraps the Runnable.

In other words, you are wrapping your FutureTask in another FutureTask. There are two ways to solve this

  1. Use

    workers[i] = new CallableWorkerThread(random.nextInt(100));
    executor.submit(workers[i]);
    

    to let the ExecutorService wrap your Callable inside a FutureTask.

  2. Use

    workers[i] = new CallableWorkerThread(random.nextInt(100));
    executor.execute(new FutureTask<Integer>(workers[i]));
    

    to wrap the Callable manually and enqueue it as Runnable without further wrapping (note the use of execute rather than submit)

Since you want to enable retrieval of the original Callable, the second option is for you, as it gives you full control over the FutureTask instance:

static class MyFutureTask<T> extends FutureTask<T> {
    final Callable<T> theCallable;

    public MyFutureTask(Callable<T> callable) {
        super(callable);
        theCallable=callable;
    }
}

submitting code:

    for (int i=0; i< workers.length; i++){
        workers[i] = new CallableWorkerThread(random.nextInt(100));
        executor.execute(new MyFutureTask<Integer>(workers[i]));
    }

RejectedExecutionHandler:

class RejectionHandlerImpl implements RejectedExecutionHandler{
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        if(r instanceof MyFutureTask) {
            MyFutureTask<?> myFutureTask = (MyFutureTask)r;
            Callable<?> c=myFutureTask.theCallable;
            System.out.println(c);
        }
        else System.out.println(r);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!