"Java Concurrency" executor framework

Source: Internet
Author: User

Introduction to the Executor framework

Java threads are both a unit of work and an execution mechanism. Starting with JDK5, the unit of work is separated from the execution mechanism.

The executor framework consists of 3 major parts

    • Task.

      • Interfaces to be implemented by the task being performed: Runnable interface or callable interface

      • The result of an asynchronous calculation. The future interface and the Futuretask class.

    • The execution of the task. Two key classes of Threadpoolexecutor and Seheduledthreadpoolexecutor.

Task Runnable Interface

Does not contain running results

 Public Interface Runnable {    publicabstractvoid  run ();}
Callable interface

Contains running results

 Public Interface Callable<v> {    throws  Exception;}

The difference between runnable and callable

The difference between runnable and callable is that
(1) The method prescribed by callable is call (), and the method specified by runnable is run ().

(2) Callable can return a value after a task is executed, and Runnable's task cannot return a value.

(3) Call method can throw an exception, the Run method can not

(4) Run callable task can get a future object, the future represents the result of an asynchronous calculation.

Future interface

The future interface represents the result of an asynchronous calculation, and the method provided by the future interface allows you to see whether the asynchronous computation is performing or to wait for the results to be executed and to get the results of the execution, while also canceling execution.

 Public InterfaceFuture<v> {    BooleanCancelBooleanmayinterruptifrunning);//Cancel a task    BooleanIsCancelled ();//is it canceled?    BooleanIsDone ();//whether the task is complete//Gets the result of the task execution, blocking the wait until the task is completed if the task is not completedV get ()throwsinterruptedexception, executionexception; //wait for some time to try to get the results of the executionV Get (LongTimeout, timeunit unit)throwsinterruptedexception, Executionexception, timeoutexception;}

A simple example of using runnable

Importjava.util.concurrent.*; Public classTest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {FinalExecutorservice exec = Executors.newfixedthreadpool (5); Runnable Task=NewRunnable () { Public voidrun () {Try{System.out.println (Thread.CurrentThread (). GetName ()+ "is running"); Thread.Sleep (1000 * 10);//Hibernate the specified time, which indicates that the operation is time-consuming}Catch(interruptedexception e) {e.printstacktrace ();        }            }        };        Exec.submit (Task); //Close the thread poolExec.shutdown (); }}

A simple example of using callable

Importjava.util.concurrent.*;  Public classTest { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {FinalExecutorservice exec = Executors.newfixedthreadpool (5); Callable<String> call =NewCallable<string>() {             PublicString Call ()throwsException {thread.sleep (1000 * 10);//Hibernate the specified time, which indicates that the operation is time-consuming                return"Important but longtime things.";        }        }; Future<String> task =Exec.submit (call); //the important thingSYSTEM.OUT.PRINTLN ("Let's do important things. Start); Thread.Sleep (1000 * 3); System.out.println ("Let's do important things." End); //something that's not important.         while(!Task.isdone ()) {System.out.println ("Still Waiting ..."); Thread.Sleep (1000 * 1); } System.out.println ("Get sth ...."); String obj=Task.get ();        System.out.println (obj); //Close the thread poolExec.shutdown (); }}

Run results

Let's do important things. Startlet ' s do important things. Endstill waiting....still waiting....still waiting....still waiting....still waiting....still Waiting....still Waiting....get sth .... Important but longtime things.
The execution mechanism of the task Threadpoolexecutor

Threadpoolexecutor is the core class of the executor framework and is the implementation class of the thread pool.

Core configuration parameters include

Corepoolsize: Size of the core thread pool

Maximumpoolsize: Size of the maximum thread pool

Blockingqueue: Temporarily save a task's work queue

Rejectedexecutionhandler: Handler that will be executed when Threadpoolexecutor is already saturated (the maximum thread pool size is reached and the work queue is full).

     Public Threadpoolexecutor (int  corepoolsize,                               int  maximumpoolsize,                              Long  KeepAliveTime,                               timeunit unit,                              blockingqueue<Runnable> workQueue) {          This (Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,             executors.defaultthreadfactory (), DefaultHandler);    }

You can create 3 types of threadpoolexecutor.

    • Fixedthreadpool

    • Singlethreadexecutor

    • Cachedthreadpool

1.FixedThreadPool

Fixedthreadpool is a thread pool with a fixed number of threads, with nthreads threads in most thread pools.

 Public Static Executorservice newfixedthreadpool (int  nthreads) {        returnnew// Nthreads is a fixed number of threads                                      // Idle thread has a wait time of 0ms, indicating immediate termination                                      New // Task Force column    }

Fixedthreadpool Execute () method internal execution procedure

    1. Create a new thread to perform a task when a new task is committed, if the current number of running threads is less than ntheads

    2. If the number of threads currently running equals the maximum number of threads set Nthreads, new tasks are added to the work queue Linkedblockingqueue

    3. The thread will repeatedly get new task executions from Linkedblockingqueue after the task has finished executing

    4. There are no new tasks in linkedblockingqueue, threads are idle, and threads are terminated.

Note the point:

Because the work queue uses a unbounded queue Linkedblockingqueue,fixedthreadpool does not reject the task (the Rejectedexecutionhandler.rejectedexecution () method is not called).

2.SingleThreadExecutor

Singlethreadexecutor is a special case of fixedthreadpool, thread pool threads have a fixed number of 1, that is, a maximum of one thread.

 Public Static Executorservice Newsinglethreadexecutor () {        returnnew  Finalizabledelegatedexecutorservice            (new threadpoolexecutor (1, 1,  //  Nthreads is a fixed number of threads                                    // idle thread Waiting time is 0ms, indicating immediate termination of                                    new//  Work Queue    }

Singlethreadexecutor's Execute () method internal execution procedures and considerations can be referred to Fixedthreadpool.

3.CachedThreadPool

Cachedthreadpool is a thread pool that creates new threads as needed.

 Public Static Executorservice Newcachedthreadpool () {        returnnew//coolpoolsize is 0, Maxinumpoolsize is the wait time for Integer.max_value                                      // idle thread, after idle 60s is terminated                                      new/ / Task column    }

The internal running process of the Execute () method of the Cachedthreadpool

    1. When a new task is committed, the main thread inserts the task into the work queue (Synchronousqueue's offer () method), and if the thread pool has idle threads waiting for the task, the new task is handed over to the idle thread.

    2. Create a new thread to perform a task if the thread pool does not have idle threads waiting on the task

    3. After the thread finishes the task, wait for the 60s (Synchronousqueue.poll (Timeunit.seconds) method), and if no new task is waiting, the thread terminates

Synchronousqueue is a blockingqueue with no capacity. Each insert operation must wait for the removal of another thread.

Cachedthreadpool uses Synchronousqueue to pass the task submitted by the main thread to the idle thread.

Note the point:

The thread pool of cachedthreadpool is non-solvable, there is no limit to the number, and if the main thread submits a task faster than the thread processing task, new threads are created continuously.

In extreme cases, the CPU and memory are exhausted by creating multithreaded threads.

Scheduledthreadpoolexecutor

Scheduledthreadpoolexecutor is primarily used for scheduled tasks (scheduled execution, execution after a given delay)

Execution Mode 1.scheduleAtFixedRate

Tasks are performed on a fixed cycle, such as set to execute every 10 minutes, the first time in the 8th minute, and the next execution point for 18 minutes, 28 minutes, and 38th minutes

 Public // Task                                                  Long // Initial delay                                                  Long // task execution Cycle                                                  Timeunit unit)
2.scheduleWithFixedDelay

Tasks follow a fixed delay, such as setting a delay time of 10 is the minute, the 8th minute executes the first time, after the task execution completes, waits 10 minutes, executes the next time. If the task executes for 2 minutes, the next time is the 20th minute

 Public scheduledfuture<?> schedulewithfixeddelay (Runnable command,/ / task                                                     Long//  Initial delay                                                     long// task Execution delay                                                     
Implementation principle

Data

Scheduledthreadpoolexecutor: Timed Task Actuator

Delayqueue: Use Delayqueue as the task queue, save the tasks to be dispatched, and the tasks are sorted by the point in time of execution. Delayqueue internal is implemented with Priorityqueue.

Scheduledfuturetask: Task to be dispatched.

Member variables for Scheduledfuturetask:

    • Time: The exact period at which the task will be executed

    • SequenceNumber: Task Sequence number, time phase, small number of first execution

    • Period: Interval of task execution

Operating mechanism

Scheduledthreadpoolexecutor Internal Operation Process

    1. The thread gets from Delayqueue to the expiring scheduledfuturetask, which means time is greater than or equal to the current.

    2. Perform task Scheduledfuturetask

    3. Modify the time of the scheduledfuturetask to go back to delayqueue for the next execution

"Java Concurrency" executor framework

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.