Executor Framework (II)

Source: Internet
Author: User

This section is from the "Java Concurrent Programming Combat" 6.2 section. Feel very good to speak but many places still do not understand, think still need solid foundation and more relevant experience to be able to understand thoroughly. Preface

A task is a set of logical units of work, and a thread is the mechanism by which a task executes asynchronously. in the Java class Library, the main abstraction that threads perform is executor, notthread. Executor source code and:

Package java.util.concurrent;

Public interface Executor {
    void execute (Runnable command);
}
Executor interface mainly implements interface/class


The above figure shows the advantages of the Executor interface: it provides the basis for the asynchronous task execution framework, supports many different types of task execution strategies, and runnable represents a task-a set of logical work units; Executor based on producer-consumer mode: The task of submitting the tasks is the producer, the thread that executes the task is the consumer ; provides support for lifecycle , statistical information collection , application management mechanisms , and performance monitoring and other mechanisms; a Web server based on executor

A Web server based on a thread pool:

public class Taskexecutionwebserver {
    private static final int nthreads=100;
    private static final Executor exec
            = Executors.newfixedthreadpool (nthreads);

    public static void Main (string[] args) throws IOException {ServerSocket socket=new
        (n);
        while (true) {
            final Socket connection=socket.accept ();
            Runnable task= (()-> System.out.println ("do somethings");
            Exec.execute (Task);}}

Changing the impact of a executor implementation or configuration is far less than changing the way the task is submitted
Executor to start a new thread for each request:

public class Threadpertaskexecutor implements Executor {
    @Override public
    void execute (Runnable command) C15/>new Thread (command). Start ();//Asynchronous Execution
    }
}

Executor to perform all tasks synchronously

public class Withinthreadexecutor implements Executor {
    @Override public
    void execute (Runnable command) {
        Command.run ();//Synchronous Execution
    }
}
two. Implementation Strategy

By decoupling the task's submission and execution , you can easily modify the execution strategy. The implementation strategy has "what, four aspects of where, when, and how to perform tasks in what thread, in what Order: FIFO, FIFO, priority, how many tasks can be executed concurrently, how many tasks are queued for execution, and when a system overload is required to reject a task. Choose which one to reject and how to notify the application that the task is rejected;
  The best execution strategy depends on the computing resources available and the quality of service requirements. Limiting the number of concurrent tasks ensures that the program does not hesitate to crash the resource exhaustion or to impact performance in the event of a competition from the demand resource provider. three. Thread pool and Work queue

The thread pool has many worker threads that perform tasks (worker thread), threads how many thread pool types to determine (such as fixed, single, scheduled, and cache), and worker threads in the thread pool are generated by the threading factory.
Work queues, which are saved in Java in all blocking queues that wait for the task to be performed.
Performing tasks in the thread pool is better than assigning a thread to each person. By reusing threads, you can allocate the huge overhead of thread creation destruction to multiple requests it handles, and the thread already exists when subsequent requests arrive, and can be improved accordingly. The proper number of threads can be that the processor remains busy, and it does not deplete memory by increasing the resources of too many threads. Four. The basic creation method of thread pool and its advantages and disadvantages

The following methods are "factory methods":
1. Newfixedthreadpool: Each commit a task to create a thread, until the maximum "fixed length", if the thread because of the exception end, the thread pool will be added to the threads;
2. Newcachethreadpool: single-threaded thread pool/executor, and if it ends, a thread is added. It ensures that tasks are performed in the order in which they are queued (fifo/lifo/priority);
3. Newscheduledthreadpool: Fixed length, timed execution-support scheduling based on relative time; thread factory and line pool

A known factory pattern can reduce coupling, as object execution and object creation can be separated. Thread creation in the Java class Library also uses the Factory mode, Threadfactory interface source code is as follows:

Package java.util.concurrent;


Public interface Threadfactory {

    /**
     * Creates a thread containing the task;
    /Thread Newthread (Runnable R);
}

The above java.util.concurrent.Executors many factory methods in the creation of thread pools (executor and their implementation classes) are used in threading factories, which can be specified You can also use the static internal class defaultthreadfactory-default factory in executors to implement the thread factory, the source code is as follows:

    /** * defined in executors * The default thread factory/Static class Defaultthreadfactory implements T  Hreadfactory {private static final Atomicinteger Poolnumber = new Atomicinteger (1);/thread pool serial number private final Threadgroup group;//Thread Line Group Private final Atomicinteger threadnumber = new Atomicinteger (1);//thread serial number Priva Te final String nameprefix;//thread name prefix//default constructor initialization: Thread group object, named Prefix defaultthreadfactory () {//todo Sec
            What is Uritymanager? securitymanager s = System.getsecuritymanager (); Group = (s!= null)?
            S.getthreadgroup (): Thread.CurrentThread (). Getthreadgroup ();//thread group reference to its thread group object Nameprefix = "pool-" + poolnumber.getandincrement () + "-thread-";/thread Front Prefix assignment}//Thread factory main methods: 1. Create thread objects: Group information, task runnable, naming; 2. Set to non-daemon; 3. Set to medium priority; public thread Newthread (Runn Able R) {//runnableInitialize thread object Threads t = new Thread (group, R, Nameprefix + THREADNUMBER.GETANDINCR
            Ement (), 0);
            Set to ' Non daemon ' if (T.isdaemon ()) T.setdaemon (false);
            Set to General priority if (T.getpriority ()!= thread.norm_priority) t.setpriority (thread.norm_priority);
        return t; }
    }

To create a "fixed-line pool" For example, its source code is as follows:

    public static Executorservice newfixedthreadpool (int nthreads) {
        //bottom or a thread pool executor that executes the length nthreads return
        New Threadpoolexecutor (Nthreads, Nthreads,
                                      0L, Timeunit.milliseconds,
                                      new linkedblockingqueue<runnable> ());
    }

The constructor of the call is as follows:

    Public threadpoolexecutor (int corepoolsize,
                              int maximumpoolsize,
                              long KeepAliveTime,
                              timeunit Unit,
                              blockingqueue<runnable> Workqueue) {This is
        (Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, Workqueue,
             executors.defaultthreadfactory (), DefaultHandler);/This is to invoke the default factory in executors that implements the Threadfactory interface
    
 Public threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, Blockingqueue<runnab Le> Workqueue, Threadfactory threadfactory, Rejectedexecuti
            Onhandler handler) {if (Corepoolsize < 0 | | |
            Maximumpoolsize <= 0 | |
            Maximumpoolsize < Corepoolsize | |
        KeepAliveTime < 0) throw new IllegalArgumentException ();
        if (Workqueue = null | | threadfactory = NULL | | | | handler = NULL) throw new NullPointerException ();
        This.corepoolsize = corepoolsize;
        This.maximumpoolsize = maximumpoolsize;
        This.workqueue = Workqueue;
        This.keepalivetime = Unit.tonanos (KeepAliveTime);
        This.threadfactory = threadfactory;
    This.handler = handler; }
five. Executor declaration cycle: Run, close, and terminated

The Executorservice class extends the Executor class and adds some methods for declaring cycle management:

Package java.util.concurrent;

    Public interface Executorservice extends Executor {void shutdown ();

    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 Interr

    Uptedexception;
                                  <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, Executione

    Xception;
      <T> T invokeany (collection<? extends callable<t>> tasks,              Long timeout, timeunit unit) throws Interruptedexception, Executionexception, timeoutexception;
 }

Three states of the Executorservice life cycle: Running: Executorservice is running while initializing; closing is a process: a gentle shutdown executorservice no longer accepting new tasks. And wait for the execution of the old task to end; a rough shutdown attempts to cancel all running tasks; After the shutdown, when all the tasks have been executed, the Executorservice arrives at the end state;
In the closed state, the submitted characters will be processed by the interface Java.util.concurrent.RejectedExecutionHandler. Its source code is as follows:

Package java.util.concurrent;

Public interface Rejectedexecutionhandler {

    /**
     * @param r The runnable task requested to be executed
     * @param Executor the executor attempting to execute this task
     * @throws Rejectedexecutionexception If there is no remedy
     *
    /void Rejectedexecution (Runnable R, Threadpoolexecutor executor);
}

Or yes, the executor interface's Execute method throws a Rejectedexecutionexception exception to its associated method:

    Wait so long: length and Time unit, returns True if Executorservice terminates, otherwise returns false;
    Boolean awaittermination (long timeout, timeunit unit)
        throws Interruptedexception;

    Whether it is in the "terminated" state, where all the characters have ended a
    boolean isterminated ();
    Causes Executorservice to be in a closed state
    void shutdown ();

Web server that supports shutdown operations

Class lifecyclewebservice{
    private finale executorservice exec= ... ; public

    void Start () throws ioexception{
        ServerSocket socket=new serversocket ();
        while (!exec.isshutdown ()) {//. is not in a closed state.
            try{
                final Socket conn=socket.accept ();
                Exec.execute (New Runnable () {public
                    void run {handlerequest (conn);}}
                );
            catch (Rejectedexecutionexception e) {
                if (!exec.isshutdown ())
                    log ("task submission rejected", e);
            }
        }
    }

    public void Stop () {Exec.shutdown ();}

    void HandleRequest (Socket connection) {
        Request req=readrequest (connection);
        if (Isshutdownrequest (req))
            stop ();
        else
            dispatchrequest (req);
    }
}
Six. Cycle tasks and deferred tasks

Deferred tasks and cycle tasks can be created by using a timer or scheduledthreadpoolexecutor (either through its constructors or Executors.newscheduledthreadpool factory methods). The
Timer class can only create one thread and does not catch exceptions, so throwing unchecked exceptions terminates the execution of the thread and does not restore the execution of the thread. The
is known from the above illustration that Scheduledthreadpoolexcutor is a class that inherits the Threadpoolexecutor class and implements the Scheduledexecutorservice interface. There are only two factory methods that construct a "cycle thread pool" in the
Executurs, respectively: You can specify the number of threads in the thread pool to be saved-even if they are idle; and specify the number of threads in the thread pool to be saved with the threading engineering class. However, the maximum number of threads in the thread pool is integer.max_value, which has the risk of memory overflow. Therefore, it is recommended that you use the Scheduledthreadpoolexecutor constructor directly--it appears that his constructor does not support specifying the maximum number of threads. Ali manual examples are as follows:

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.