ExecutorService interface in java

Source: Internet
Author: User

I. Statement

Public interfaceExecutorServiceThe extends Executor is located under the java. util. concurrent package.

All super interfaces:Executor

All known sub-interfaces:ScheduledExecutorService

All known implementation classes:AbstractExecutorService, ScheduledThreadPoolExecutor, ThreadPoolExecutor

Ii. Overview

ExecutorProvides a method for managing termination and can be generated to track the execution status of one or more asynchronous tasksFuture.

Can be disabledExecutorServiceThis will cause it to reject the new task. Two methods are provided to disableExecutorService.shutdown()The method allows you to execute previously submitted tasks before termination, whileshutdownNow()Method To prevent waiting for the task to start and attempting to stop the task currently being executed. When the program is terminated, No task is being executed, No task is waiting for execution, and a new task cannot be submitted. Disable unusedExecutorServiceTo allow recycling of its resources.

After creation, return a message that can be used to cancel execution and/or wait for completion.Future, MethodSubmitExtended Basic MethodsExecutor.execute(java.lang.Runnable). MethodInvokeAnyAndInvokeAllIs the most common form of batch execution, they execute the collection task, and then wait for at least one, or all the tasks to complete (can be used)ExecutorCompletionServiceClass ).

ExecutorsClass provides a factory method for the execution program service provided in this package.

The following shows a simple structure of the network service. Here, the thread in the thread pool serves as the incoming request. It uses pre-configuredExecutors.newFixedThreadPool(int)Factory method:

 class NetworkService implements Runnable {    private final ServerSocket serverSocket;    private final ExecutorService pool;    public NetworkService(int port, int poolSize)        throws IOException {      serverSocket = new ServerSocket(port);      pool = Executors.newFixedThreadPool(poolSize);    }     public void run() { // run the service      try {        for (;;) {          pool.execute(new Handler(serverSocket.accept()));        }      } catch (IOException ex) {        pool.shutdown();      }    }  }  class Handler implements Runnable {    private final Socket socket;    Handler(Socket socket) { this.socket = socket; }    public void run() {      // read and service request on socket    } }

The following methods are disabled in two phases:ExecutorService. Stage 1 callShutdownReject incoming tasks and then callShutdownNow(If necessary) cancel all legacy tasks:

void shutdownAndAwaitTermination(ExecutorService pool) {   pool.shutdown(); // Disable new tasks from being submitted   try {     // Wait a while for existing tasks to terminate     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {       pool.shutdownNow(); // Cancel currently executing tasks       // Wait a while for tasks to respond to being cancelled       if (!pool.awaitTermination(60, TimeUnit.SECONDS))           System.err.println("Pool did not terminate");     }   } catch (InterruptedException ie) {     // (Re-)Cancel if current thread also interrupted     pool.shutdownNow();     // Preserve interrupt status     Thread.currentThread().interrupt();   } }

Memory consistency effect: thread OrientationExecutorServiceSubmitRunnableOrCallableOperations before a taskHappen-beforeAll operations extracted by the task, followedHappen-beforePassFuture.get()Result.

Start with the following versions:1.5

Iii. Detailed Method

1. voidShutdown()

Start and close the task in sequence, and execute the previously submitted task, but do not accept the new task. If it is disabled, the call has no other effect.

Throw: SecurityException-If the security manager exists and is disabled, ExecutorService may operate some threads that are not allowed to be modified by the caller (because it is not maintained ).RuntimePermission("ModifyThread ")), Or the security manager'sCheckAccessMethod.

2. List ShutdownNow() Try to stop all ongoing activity tasks, pause processing pending tasks, and return to the list of pending tasks.

It cannot be guaranteed that the task being processed can be stopped, but it will try its best. For exampleThread.interrupt()To cancel the typical implementation, so any task that cannot respond to the interruption may never be terminated.

Return Value:List of tasks that have never started

Throw: SecurityException-If the security manager exists and is disabled, ExecutorService may operate some threads that are not allowed to be modified by the caller (because it is not maintained ).RuntimePermission("ModifyThread ")), Or the security manager'sCheckAccessMethod.

3. booleanIsShutdown() If the execution program is closed, returnTrue.

4. booleanIsTerminated() If all tasks are completed after the task is closedTrue. Note that unless you callShutdownOrShutdownNowOtherwiseIsTerminatedNeverTrue.

5. booleanAwaitTermination(Long timeout, TimeUnit unit) throws InterruptedException

When a request is closed, times out, or the current thread is interrupted, no matter which one occurs first, it will cause blocking until all tasks are completed.

Parameters:timeout-Maximum waiting time

unit-Timeout parameter time unit

Return Value:If the execution program is terminated, returnTrueIf the timeout period expires before termination, returnFalse

Throw:InterruptedException-If an interruption occurs while waiting

6, Future Submit(Callable Task)

The task that submits a returned value is used for execution and returns a Future indicating the outstanding results of the task. The FutureGetThe method returns the result of the task when it is successfully completed.

You can useResult = exec. submit (aCallable). get ();Form.

Note:ExecutorsClass includes a set of methods that can be used to convert some other common objects similar to closures. For examplePrivilegedActionConvertCallableTo submit them.

Parameters: task-Task to be submitted

Return Value:Indicates the Future of the task waiting for completion.

Throw: RejectedExecutionException-If the task cannot be scheduled

NullPointerException-If the task is null

7, Future Submit(Runnable task, T result)

Submit a Runnable task for execution and return a Future indicating the task. The FutureGetThe method returns the given result when it is successfully completed.

Parameters: task-Task to be submittedresult-Returned results

Return Value:Indicates the Future of the task waiting for completion.

Throw: RejectedExecutionException-If the task cannot be scheduled

NullPointerException-If the task is null

8. Future Submit(Runnable task)

Submit a Runnable task for execution and return a Future indicating the task. The FutureGetMethod inSuccessfulWill returnNull.

Parameters:task-Task to be submitted

Return Value:Indicates the Future of the task waiting for completion.

Throw:RejectedExecutionException-If the task cannot be scheduled

NullPointerException-If the task is null

9, List > InvokeAll(Collection > Tasks) throws InterruptedException

Execute a given task. When all tasks are completed, the Future list that maintains the task status and result is returned. ReturnsFuture.isDone()IsTrue. Note that it can be terminated normally or by throwing an exceptionCompletedTask. If the given collection is modified while performing this operation, the result of this method is uncertain.

Parameters:tasks-Task collection

Return Value:Indicates the Future list of tasks. The list order is the same as that generated by the iterator in the given task list. Each task has been completed.

Throw:InterruptedException-If an interruption occurs while waiting, in this case, the unfinished task is canceled.

NullPointerException-If a task or any of its elements isNull

RejectedExecutionException-If all tasks cannot be scheduled

10, List > InvokeAll(Collection > Tasks, long timeout, TimeUnit unit) throws InterruptedException

When a given task is executed, when all tasks are completed or time-out expires (no matter which occurs first), the Future list of the task status and result is returned. ReturnsFuture.isDone()IsTrue. Once a task is returned, the task that has not been completed is canceled. Note that it can be terminated normally or by throwing an exceptionCompletedTask. If the given collection is modified while this operation is in progress, the result of this method is uncertain.

Parameters:tasks-Task collectiontimeout-Maximum waiting timeunit-Timeout parameter time unit

Return Value:Indicates the Future list of tasks. The list order is the same as that generated by the iterator in the given task list. If the operation does not time out, all tasks have been completed. If the task times out, some tasks have not been completed.

Throw:InterruptedException-If an interruption occurs while waiting, in this case, cancel the unfinished task.

NullPointerException-If the task or any of its elements or unit isNull

RejectedExecutionException-If all tasks cannot be scheduled

11, T InvokeAny(Collection > Tasks) throws InterruptedException, ExecutionException

If a given task is successfully executed (that is, no exception is thrown), the result is returned. Once a normal or abnormal response is returned, the unfinished task is canceled. If the given collection is modified while this operation is in progress, the result of this method is uncertain.

Parameters:tasks-Task collection

Return Value:Result returned by a task

Throw:InterruptedException-If an interruption occurs while waiting

NullPointerException-If a task or any of its elements isNull

IllegalArgumentException-If the task is empty

ExecutionException-If no task is successfully completed

RejectedExecutionException-If the task cannot be scheduled

12, T InvokeAny(Collection > Tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

If a task is successfully completed (that is, no exception is thrown) before the specified timeout period expires, the result is returned. Once a normal or abnormal response is returned, the unfinished task is canceled. If the given collection is modified while this operation is in progress, the result of this method is uncertain.

Parameters: tasks-Task collectiontimeout-Maximum waiting timeunit-Timeout parameter time unit

Return Value:Result returned by a task

Throw: InterruptedException-If an interruption occurs while waiting

NullPointerException-If the task or any of its elements or unit isNull

TimeoutException-If the specified timeout period expires before all tasks are successfully completed

ExecutionException-If no task is successfully completed

RejectedExecutionException-If the task cannot be scheduled

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.