Java Multithreading increase six: Java5 thread pool for threading concurrent libraries

Source: Internet
Author: User

We have a certain understanding of concurrency, and know how to create threads, the creation of threads mainly rely on the thread of the class to complete, then what is the flaw? How to solve?

First, compare new Thread
The disadvantage of new thread
A. Each new thread creates a poor performance for the newly created object.
B. Lack of unified management of threads, the possibility of unlimited new threads, competing with each other, and potentially consuming excessive system resources can lead to freezing or oom.
C. Lack of additional functionality, such as timed execution, periodic execution, and thread interruption.
The benefits of the four thread pools provided by new Thread,java are:
A. Reusing existing threads, reducing the cost of object creation, extinction, and performance.
B. Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, avoid clogging.
C. Provide functions such as timed execution, periodic execution, single-threaded, concurrency control, etc.

Second, create thread pool method

The thread pool is typically created by calling executors's factory method, which is commonly used in the following 5 categories:

 //  Create a thread pool to control the maximum number of concurrent threads, and the excess threads will wait in the queue  executors.newfixedthreadpool  //  Create a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks execute  executors.newsinglethreadexecutor  //  Creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and if it is not recyclable, the new thread   //  Create a thread pool that supports timed and recurring tasks  executors.newscheduledthreadpool  //  Create a single thread pool that supports timed and recurring task execution  Executors.newsinglethreadscheduledexecutor 

Each of the above basic parameters are used, you can also join Threadfactory (Java thread Generation factory, you can rewrite the name log and so on) parameters according to your personal needs. such as: newFixedThreadPool There are two methods of overloading: newFixedThreadPool(int) andnewFixedThreadPool(int,ThreadFactory)

The call to the above method is actually to create a Threadpoolexecutor object, but only the parameters passed in different.
Threadpoolexecutor class Method: ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, ...) You can define the number of threads fixed by the thread pool and the maximum number of threads.

Third, the implementation

Typically by invoking execute(Runnable) or submit(Callable) executing a thread

Four, close

For details, refer to:
In-depth understanding of java– thread pool (ii): Shutdown, Shutdownnow, awaittermination
The difference between Java thread pool shutdown and Shutdownnow
Usage and differences of shutdown (), Shutdownnow (), Awaittermination () in Threadpoolexecutor

threadPool.shutdown(): Do not accept new tasks, the submitted tasks continue to execute

Initiates an orderly shutdown in which previously submitted
Tasks is executed, but no new tasks would be accepted.
Invocation have no additional effect if already shut down.

List<Runnable> shutdownNow(): Prevents the new task from committing, and attempts to break the currently running thread, returning the list of tasks awaiting execution

Attempts to stop all actively executing tasks, halts the
Processing of waiting tasks, and returns a list of the tasks
that were awaiting execution.

awaitTermination(long timeout, TimeUnit unit): All submitted tasks (both running and waiting in the queue) are executed or timed out or interrupted.

Thread pool Status:
isShutdown(): If this executor have been shut down.
isTerminated(): If all tasks has completed following shut down.isterminated is never true unless either shutdown or Shutdownnow were call Ed First

How to choose:
* Graceful closing, with shutdown ()
* Want to close immediately and get a list of non-executed tasks with Shutdownnow ()
* Gracefully closes and allows new tasks to be submitted after the declaration is closed, with awaittermination ()

Five, common thread pool

Newfixedthreadpool

To apply a scenario: the thread pool of fixed threads is more common, such as processing network requests. Common!!!

Using the example

/Call Executeexecutorservice Fixedthreadpool= Executors.newfixedthreadpool (3);  for(inti = 0; I < 10; i++) {      Final intindex =i; Fixedthreadpool.execute (NewRunnable () { Public voidrun () {System.out.println (index);  }); }  //Call SubmitExecutorservice Fixedthreadpool = Executors.newfixedthreadpool (3); List<Future> futurelist =NewArraylist<future>(); for(inti = 0; I < 10; i++) {    Final intindex =i; Futurelist.add (Fixedthreadpool.submit (NewCallable<integer>() {         PublicInteger Call ()throwsException {returnindex; }    }));} for(Future future:futurelist) {Try{future.get (); } Catch(Exception e) {future.cancel (true); }}
Newcachedthreadpool

Main application scenario: Requires extreme speed because Newcachedthreadpool does not wait on idle threads. However, there is a risk that if a task is slow or blocked, and a lot of requests, it is prone to the proliferation of threads, resulting in the entire system of suspended animation (unable to receive processing of new requests), so in fact, the individual is not recommended to use this method.

Use Example: Execute, submit similar to Newfixedthreadpool

Executorservice Cachedthreadpool = executors.newcachedthreadpool ();    for (int i = 0; i < ten; i++) {      finalint index = i;      Cachedthreadpool.execute (new  Runnable () {          publicvoid  Run () {              System.out.println (index);}}      );  
Newsinglethreadexecutor

Use Example: Execute, submit similar to Newfixedthreadpool

Executorservice singlethreadexecutor = executors.newsinglethreadexecutor ();    for (int i = 0; i < ten; i++) {  finalint index = i;    Singlethreadexecutor.execute (new  Runnable () {    publicvoid run () {      System.out.println (index);    });  
Newscheduledthreadpool

Executes the Newscheduledthreadpool return class Scheduledexecutorservice (in fact, the new class Scheduledthreadpoolexecutor).
Through the definition of class Scheduledthreadpoolexecutor: class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService and Source:
1, Scheduledthreadpoolexecutor is the implementation class of Scheduledexecutorservice.
2, Scheduledthreadpoolexecutor inherited the class Threadpoolexecutor

Typically we get class scheduledexecutorservice through the Executors factory method (Executors.newscheduledthreadpool) or directly through the new The Scheduledthreadpoolexecutor class creates a timed task.

Scheduledthreadpoolexecutor has the following overloaded methods:
method returns the interface: ScheduledFuture . The interface definition is: public interface ScheduledFuture<V> extends Delayed, Future<V> . There are several common ways to do this:
cancel:Cancel a task
getDelay: How long does it take to get a task

public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
Delayed delay execution, only once

Using the example

//Delay 3s executionScheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5); Scheduledthreadpool.schedule (NewRunnable () { Public voidrun () {System.out.println ("Delay 3 seconds"); }  }, 3, Timeunit.seconds); //1 seconds delay after every 3 secondsScheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5); Scheduledfuture<?> scheduledfuture = Scheduledthreadpool.scheduleatfixedrate (NewRunnable () { Public voidrun () {System.out.println ("Delay 1 seconds, and excute every 3 seconds"); }  }, 1, 3, Timeunit.seconds); //get how long the next task will be executedScheduledfuture.getdelay (Timeunit.seconds)

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
Deferred initialdelay begins execution, followed by periodic period execution, analogous to the Scheduleatfixedrate method of the timer, fixed frequency execution. When a task executes more than period time, it can cause the next scheduled task to be delayed, but there is no concurrent execution. When any of the tasks run out of the exception, the subsequent tasks will not be executed. So if you want to keep the task is always executed by the cycle, then catch all possible exceptions. The task can be stopped by canceling the task (calling the Cancel method) or terminating executor (calling the Shutdown method).

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
Deferred initialdelay begins execution, followed by periodic period execution, analogous to the schedule method of the timer, fixed delay execution. When the last task executes, wait for the delay time to execute the next, and therefore not concurrently execute the situation. When any of the tasks run out of the exception, the subsequent tasks will not be executed. So if you want to keep the task is always executed by the cycle, then catch all possible exceptions. The task can be stopped by canceling the task (calling the Cancel method) or terminating executor (calling the Shutdown method).

Six, the difference between Scheduledthreadpoolexecutor and timer

Direct reference: Timer and Scheduledthreadpoolexecutor

Reference:

Java Common thread pool
Usage analysis of Java four thread pool
The difference between Java thread pool shutdown and Shutdownnow

Java Multithreading increase six: Java5 thread pool for threading concurrent libraries

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.