Java Executor Framework Learning Summary

Source: Internet
Author: User

Most concurrency is done in a way that is performed by the task. There are generally two ways to perform tasks: serial and parallel.

Class Singlethreadwebserver {public    static void Main (string[] args) throws Exception {        ServerSocket socket = new ServerSocket (+);        while (true) {            Socket conn = socket.accept ();            HandleRequest (conn);}}}    Class Threadpertaskwebserver {public    static void Main (string[] args) throws Exception {        ServerSocket socket = new ServerSocket (+);        while (true) {            final Socket conn = socket.accept ();            Runnable task = new Runnable () {public                void run () {                    handlerequest (conn);                }            };            New Thread (Task). Start ();}}    }

Of course, both of these methods are problematic. The single-threaded problem is that concurrency is a bottleneck, and a multithreaded version is an unrestricted creation of threads that can lead to a resource shortage problem.

Executor Frame

A task is a set of logical units of work, and a thread is the mechanism by which the task executes asynchronously.

The JDK provides the Executor interface:

Public interface Executor {    void execute (Runnable command);}

Although the Executor interface is relatively simple, it is the foundation of the asynchronous task execution framework, which supports a number of different types of task execution strategies. It provides a standard way to decouple the task submission process from the execution process. Use Runnable to represent tasks. The implementation of Executor provides mechanisms for lifecycle support and statistical information application Management.

Executor is based on the producer-consumer model, where the task is submitted as the producer and the thread performing the task is equivalent to consumption.

Examples of WebServer based on Executor are as follows:

public class Taskexecutorwebserver {    private static final int nthreads = +;    private static final Executor exec = Executors.newfixedthreadpool (nthreads);    public static void Main (string[] args) throws Exception {        ServerSocket serversocket = new ServerSocket (n);        while (true) {            final Socket conn = serversocket.accept ();            Runnable task = new Runnable () {                @Override public                void Run () {                    handlerequest (conn);                }            };            Exec.execute (Task);}}}    

Alternatively, you can implement Executor to control whether it is concurrency or parallelism, as in the following code:

/** * Object that executes the submitted Runnable task. * This interface provides a way to separate task submissions from the mechanics of how each task will function (including details of thread usage, scheduling, and so on). * Threads are typically created using Executor instead of explicitly. * * * @author Renchunxiao * */public class Executordemo {public static void main (string[] args) {Executor exec        Utor = new Threadexecutor ();            Executor.execute (New Runnable () {@Override public void run () {//do something        }        });        Executor Executor2 = new Serialexecutor ();            Executor2.execute (New Runnable () {@Override public void run () {//do something    }        }); }}/** * Create a thread to execute command * * @author Renchunxiao * */class Threadexecutor implements Executor {@Override public vo    ID execute (Runnable command) {new Thread (command). Start (); }}/** * Serial Execution Command * * @author Renchunxiao * */class Serialexecutor implements Executor {@Override public void ex    Ecute (Runnable command) {command.run (); }}
Thread pool

A thread pool is a resource pool of threads that can be created through a static factory method in executors.

    • Newfixedthreadpool. Create a fixed-length thread pool, each time a task is committed to create a thread, until the maximum number of thread pools is reached, the size of the thread pool no longer changes.
    • Newsinglethreadexecutor. A single thread pool.
    • Newcachedthreadpool. A thread pool that changes according to the size of the task.
    • Newscheduledthreadpool. Creates a fixed-length thread pool that performs tasks in a deferred or timed manner.

The JVM exits only after all non-daemon threads have been terminated, so the JVM cannot end if Executor is not properly closed.

In order to solve the life cycle problem of service execution, there is a new interface Executorser vice that extends the Executor interface.

Public interface Executorservice extends Executor {void shutdown ();    List<runnable> Shutdownnow ();    Boolean IsShutDown ();    Boolean isterminated ();    Boolean awaittermination (long timeout, timeunit unit) throws Interruptedexception;    <T> future<t> Submit (callable<t> Task);    <T> future<t> Submit (Runnable task, T result);    Future<?> Submit (Runnable Task); <T> list<future<t>> InvokeAll (collection<? extends callable<t>> tasks) throws Interru    Ptedexception;                                  <T> list<future<t>> InvokeAll (collection<? extends callable<t>> tasks,    Long timeout, timeunit unit) throws Interruptedexception; <T> T invokeany (collection<? extends callable<t>> tasks) throws Interruptedexception, Executionex    ception; <T> T Invokeany (collection<? extends callable<t>> tasks, long TImeout, Timeunit unit) throws Interruptedexception, Executionexception, TimeoutException;} 

The Executorservice life cycle has three states: run, off, terminated. The Executorservice is in the running state at the time of initial creation. The shutdown method gently shuts down: does not accept new tasks, and waits for tasks that have already been performed to complete (including those that have not yet started). The Shutdownnow method will be brutally closed: it will attempt to cancel all running tasks and no longer start tasks in the queue that have not yet started. All tasks are completed and entered into the terminated state.

Callable and future

The Executor framework uses Runnable as a basic task representation. Runnable is a limited abstraction, and its run method cannot return a value and throws a checked exception.

Many tasks are actually deferred computations, such as database queries, which fetch resources from the network. For these tasks, callable is a better abstraction, and it thinks that call will return a value and may throw an exception.

The tasks performed by Executor have four life cycle phases: Create, submit, start, and finish. Because some tasks take a long time to be possible to cancel, in the Executor framework, a task that has been submitted for not starting can be canceled.

The future represents the life cycle of a task and provides a way to determine whether it has been completed or canceled, and to obtain the results of the task and cancel the task.

Java Executor Framework Learning Summary

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.