Abstractexecutorservice provides a default implementation for Executorservice methods that perform task types. These methods include Submit,invokeany and InvokeAll.
Note that the Execute method from the executor interface is not implemented, the Execute method is the core of the whole system, and all tasks are actually executed in this method, so different implementations of the method will bring different execution strategies. This can be seen in the back analysis of Threadpoolexecutor and Scheduledthreadpoolexecutor.
First look at the Submit method, and its basic logic is this:
1. Generate a task type and a wrapper interface for the future interface Runnablefuture objects
2. Perform Tasks
3. Return to the future.
PublicFuture<?>Submit (Runnable Task) {if(Task = =NULL)Throw NewNullPointerException (); Runnablefuture<Void> ftask = newtaskfor (Task,NULL); Execute (ftask); returnFtask; } Public<T> future<t> Submit (callable<t>Task) { if(Task = =NULL)Throw NewNullPointerException (); Runnablefuture<T> Ftask =newtaskfor (Task); Execute (ftask); returnFtask; }
Because submit supports callable and runnable two types of tasks, the Newtaskfor method has two overloaded methods:
protected <T> runnablefuture<t> newtaskfor (callable<t> callable) { Returnnew futuretask<t>(callable); } protected <T> runnablefuture<t> newtaskfor (Runnable Runnable, T value) { Returnnew futuretask<t>(runnable, value); }
As I said in the previous article, the difference between callable and Runnable is that the former has a return value, that is, the callable=runnable+ return value. So Java provides a adapter that converts the Runnable+ return value to the callable type. This can be seen in the code for the constructor of the Futuretask type in newtaskfor:
Public Futuretask (callable<v> callable) { ifnull) throw New nullpointerexception (); New Sync (callable); } Public Futuretask (Runnable Runnable, V result) { new Sync (executors.callable (Runnable, result)); }
The following is the code for the executors.callable method:
Public static <T> callable<t> callable (Runnable task, T result) { ifnull ) thrownew nullpointerexception (); return New Runnableadapter<t>(task, result); }
Then the Runnableadapter code is well understood, it is a callable implementation, the call method implementation is to execute the runnable run method, and then return the value.
static final class runnableadapter<t> implements Callable<t> { final Runnable task; final T result; Runnableadapter (Runnable task, T result) { task; this . Result = result; public T call () {Task.run () ; return result; } }
Now let's talk about the simpler InvokeAll:
1. Call the Newtaskfor method for each task to generate a list of wrapper class objects that are both task and future
2. Loop invoke execute to perform each task
3. Loop through each future's get method again to wait for each task to finish executing
4. Finally, return to the list of future.
Public<T> list<future<t>> InvokeAll (collection<?extendsCallable<t>>Tasks,LongTimeout, timeunit unit)throwsinterruptedexception {if(Tasks = =NULL|| Unit = =NULL) Throw NewNullPointerException (); LongNanos =Unit.tonanos (timeout); List<Future<T>> futures =NewArraylist<future<t>>(Tasks.size ()); BooleanDone =false; Try { //generate wrapper objects for each task for(callable<t>t:tasks) Futures.add (newtaskfor (t)); LongLasttime =System.nanotime (); //Loop calls execute to execute each method//this is because the time-out is set, so after each execution//Check if the timeout is exceeded and return to the future collection directlyIterator<future<t>> it =Futures.iterator (); while(It.hasnext ()) {Execute ((Runnable) (It.next ())); Longnow =System.nanotime (); Nanos-= Now-Lasttime; Lasttime=Now ; if(Nanos <= 0) returnfutures; } //wait for each task to finish executing for(future<t>f:futures) { if(!F.isdone ()) { if(Nanos <= 0) returnfutures; Try{f.get (Nanos, timeunit.nanoseconds); } Catch(Cancellationexception ignore) {}Catch(Executionexception ignore) {}Catch(timeoutexception toe) {returnfutures; } Longnow =System.nanotime (); Nanos-= Now-Lasttime; Lasttime=Now ; }} Done=true; returnfutures; } finally { if(!Done ) for(future<t>f:futures) F.cancel (true); } }
Finally, the difficulty of Invokeany is that as long as a task executes successfully, it is returned and other tasks are canceled, which means that the focus is on finding the first task to perform successfully.
Here I think of Blockingqueue, when all the tasks are committed, the future of the task execution is added to a blockingqueue, and then the first way to perform a successful task is to remove the first element from Blockingqueue. This is the basic principle of the executorcompletionservice used by the Doinvokeany method.
Because the two Invokeany methods call the Doinvokeany method, the following is the code analysis for Doinvokeany:
Private<T> T doinvokeany (collection<?extendsCallable<t>>Tasks,BooleanTimedLongNanos)throwsinterruptedexception, Executionexception, timeoutexception {if(Tasks = =NULL) Throw NewNullPointerException (); intNtasks =tasks.size (); if(Ntasks = = 0) Throw Newillegalargumentexception (); List<Future<T>> futures=NewArraylist<future<t>>(Ntasks); //Executorcompletionservice is responsible for performing the task, followed by a call to return the first execution result with pollexecutorcompletionservice<t> ECS =NewExecutorcompletionservice<t> ( This); //for efficiency reasons, each time a task is submitted, check that there are no completed tasks. Try{executionexception ee=NULL; LongLasttime = timed? System.nanotime (): 0; Iterator<?extendsCallable<t>> it =Tasks.iterator (); //submit a task firstFutures.add (Ecs.submit (It.next ())); --Ntasks; intActive = 1; for (;;) { //try to get an execution result (the result is returned immediately)Future<t> f =Ecs.poll (); //no results were executed if(f = =NULL) { //If another task is not committed, submit a task if(Ntasks > 0) { --Ntasks; Futures.add (Ecs.submit (It.next ())); ++active; } //No task was carried out, and there was no successful result. Else if(Active = = 0) Break; //If a timeout condition is set Else if(timed) {//wait for the result to be executed until there is a result or timeoutf =Ecs.poll (Nanos, timeunit.nanoseconds); if(f = =NULL) Throw Newtimeoutexception (); //the update here is not very small, because this future may be the failure of execution, then you need to wait for the next result again, the time-out setting or need to use. Longnow =System.nanotime (); Nanos-= Now-Lasttime; Lasttime=Now ; } //no timeout is set and all tasks are committed, wait until the first execution results ElseF=Ecs.take (); } //there is a return result, try to get the result from the future, if it fails, then we need to wait for the next execution result if(F! =NULL) { --active; Try { returnF.get (); } Catch(executionexception EEx) {ee=EEx; } Catch(RuntimeException Rex) {EE=NewExecutionexception (Rex); } } } //Executorcompletionservice An error occurred while executing, returning all null future if(EE = =NULL) EE=Newexecutionexception (); Throwee; } finally { //try to cancel All tasks (no effect on tasks that have already been completed) for(future<t>f:futures) F.cancel (true); } }
followed by analysis of Threadpoolexecutor and Scheduledthreadpoolexecutor.