Java class library

Source: Internet
Author: User

1 CountDownLatch
CountDownLatch is a countdown lock. When the countdown reaches 0, the event is triggered, that is, unlocking. Other people can enter.
In some application scenarios, you need to wait for a condition to meet the requirements before doing the following. At the same time, when the thread is complete, the event is triggered for subsequent operations.
CountDownLatch the most important methods are countDown () and await (). The former is mainly the reciprocal, and the latter is waiting for the reciprocal to 0. If it does not reach 0, it will only wait for blocking.
The example below briefly describes how to use CountDownLatch to simulate a 100-meter race. ten contestants are ready, and only wait for the referee to give an order. When everyone reaches the finish point, the game is over.
Package com. eyesmore. concurrent;

Import java. util. concurrent. CountDownLatch;
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;

Public class CountDownLatchDemo {

Private static final int PLAY_AMOUNT = 10;

Public static void main (String [] args ){

/*
* Start: as long as the referee says "start", all runners can start running.
**/
CountDownLatch begin = new CountDownLatch (1 );

/*
* When each player reaches the end, it will report one arrival. When all the players arrive, the competition will end.
**/
CountDownLatch end = new CountDownLatch (PLAY_AMOUNT );
Player [] plays = new Player [PLAY_AMOUNT];
For (int I = 0; I <PLAY_AMOUNT; I ++ ){
Plays [I] = new Player (I + 1, begin, end );
}
ExecutorService exe = Executors. newFixedThreadPool (PLAY_AMOUNT );
For (Player p: plays) {// everybody
Exe.exe cute (p );
}
System. out. println ("Start of the Competition ");
Begin. countDown (); // starts the announcement
Try {
End. await (); // wait for the end
} Catch (InterruptedException e ){
E. printStackTrace ();
} Finally {
System. out. println ("the game is over ");
}

// Note: At this time, the main thread is about to end, but the exe thread will not end if it is not closed.
Exe. shutdown ();
}

}


Class Player implements Runnable {

Private int id;

Private CountDownLatch begin;

Private CountDownLatch end;

Public Player (int id, CountDownLatch begin, CountDownLatch end ){
Super ();
This. id = id;
This. begin = begin;
This. end = end;
}

Public void run (){
Try {
Begin. await (); // you must wait until the countdown of the referee reaches 0.
Thread. sleep (long) (Math. random () * 100); // simulate the time required for running
System. out. println ("Play" + id + "has arrived .");

} Catch (InterruptedException e ){
E. printStackTrace ();
} Finally {
End. countDown (); // report to the judges that the end is reached
}
}
}
 
2 ThreadPoolExecutor
The thread pool class is java. util. concurrent. ThreadPoolExecutor. The common constructor is as follows:

ThreadPoolExecutor (int corePoolSize, int maximumPoolSize,

Long keepAliveTime, TimeUnit unit,

BlockingQueue <Runnable> workQueue,

RejectedExecutionHandler handler)

CorePoolSize: Minimum number of threads maintained by the thread pool

MaximumPoolSize: Maximum number of threads maintained by the thread pool

KeepAliveTime: the idle time allowed by the thread pool to maintain the thread

Unit: the unit of idle time allowed by the thread pool maintenance thread.

WorkQueue: The Buffer Queue used by the thread pool.

Handler: processing policy of the thread pool to reject tasks

A task is added to the thread pool using the execute (Runnable) method. A task is a Runnable object. The execution method of a task is the run () method of a Runnable object.

When a task is added to the thread pool through the execute (Runnable) method:

L if the number of threads in the thread pool is smaller than corePoolSize at this time, a new thread should be created to process the added tasks even if all threads in the thread pool are idle.

2. If the number in the thread pool is equal to corePoolSize but the Buffer Queue workQueue is not full, the task is put into the buffer queue.

3. If the number in the thread pool is greater than corePoolSize, the Buffer Queue workQueue is full, and the number in the thread pool is smaller than maximumPoolSize, a new thread is created to process the added task.

4. If the number in the thread pool is greater than corePoolSize, the Buffer Queue workQueue is full, and the number in the thread pool is equal to maximumPoolSize, the handler policy is used to process the task. That is, the processing task priority is: Core Thread corePoolSize, task queue workQueue, maximumPoolSize. If all three are full, handler is used to process the rejected task.

5. When the number of threads in the thread pool is greater than corePoolSize, if the idle time of a thread exceeds keepAliveTime, the thread will be terminated. In this way, the thread pool can dynamically adjust the number of threads in the pool.

The optional parameters of unit are several static attributes in java. util. concurrent. TimeUnit:

NANOSECONDS, MICROSECONDS, MILLISECONDS, and SECONDS.

WorkQueue is commonly used: java. util. concurrent. ArrayBlockingQueue

Handler has four options:

ThreadPoolExecutor. AbortPolicy ()

Throw a java. util. concurrent. RejectedExecutionException

ThreadPoolExecutor. CallerRunsPolicy ()

Retry adding the current task and it will automatically call the execute () method again

ThreadPoolExecutor. DiscardOldestPolicy ()

Discard Old tasks

ThreadPoolExecutor. DiscardPolicy ()

Discard current task

Ii. References

An ExecutorService that uses one of several possible pool threads to execute each submitted task. It is usually configured using the Executors factory method.

The thread pool can solve two different problems: because it reduces the overhead of each task call, they can generally provide enhanced performance when executing a large number of asynchronous tasks, you can also bind and manage resources (including the threads used to execute collection tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

This class provides many adjustable parameters and extension hooks for ease of use across a large number of contexts. However, it is strongly recommended that programmers use the more convenient Executors factory method Executors. newCachedThreadPool () (unbounded thread pool, which can be automatically recycled), Executors. newFixedThreadPool (int) (fixed-size thread pool) and Executors. newSingleThreadExecutor () (a single background thread), which are predefined for most use cases. Otherwise, use the following instructions when manually configuring and adjusting the class:

Core and maximum pool size
ThreadPoolExecutor automatically adjusts the pool size based on the boundaries set by corePoolSize (see getCorePoolSize () and maximumPoolSize (see getMaximumPoolSize. When a new task is submitted in the execute (java. lang. Runnable) method, if the running thread is less than corePoolSize, a new thread is created to process the request, even if other auxiliary threads are idle. If the number of running threads is greater than corePoolSize and less than maximumPoolSize, a new thread is created only when the queue is full. If the set corePoolSize and maximumPoolSize are the same, a fixed thread pool is created. If you set maximumPoolSize to a basic unbounded value (such as Integer. MAX_VALUE), the pool is allowed to adapt to any number of concurrent tasks. In most cases, the core and maximum pool sizes are only set based on the constructor. However, you can also use setCorePoolSize (int) and setMaximumPoolSize (int) for dynamic changes.

Construct on demand
By default, you can use the prestartCoreThread () or prestartAllCoreThreads () method to dynamically override the Core Thread created and started only when the new task is required.

Create a thread
Use ThreadFactory to create a new thread. Otherwise, Executors. defaultThreadFactory () is used to create threads in the same ThreadGroup, and these threads have the same NORM_PRIORITY priority and non-daemon status. By providing different ThreadFactory, you can change the thread name, thread group, priority, and daemon status. If ThreadFactory fails to create a thread when return null from newThread, the execution program continues to run, but cannot execute any tasks.

Maintain activity time

If there are more threads in the pool than corePoolSize, these extra threads will be terminated when the idle time exceeds keepAliveTime (see getKeepAliveTime (java. util. concurrent. TimeUnit )). This provides a way to reduce resource consumption when the pool is inactive. If the pool becomes more active later, a new thread can be created. You can also use setKeepAliveTime (long, java. util. concurrent. TimeUnit) to dynamically change this parameter. Use the value of Long. MAX_VALUE TimeUnit. NANOSECONDS to effectively disable idle threads from the previous termination status before closing.

Queuing
All BlockingQueue can be used to transfer and maintain submitted tasks. You can use this queue to interact with the pool size:

A. If the number of running threads is less than corePoolSize, Executor always prefers to add new threads without queuing.

B. If the running thread is equal to or greater than corePoolSize, Executor always prefers to add requests to the queue without adding new threads.

C. If the request cannot be added to the queue, a new thread is created, unless the creation of this thread exceeds the maximumPoolSize. In this case, the task is denied.

There are three common queuing policies:
Submit directly. The default Job Queue option is SynchronousQueue, which directly submits tasks to the thread without holding them. If there is no thread that can be used to run the task immediately, trying to add the task to the queue will fail, so a new thread will be constructed. This policy prevents locking when processing a collection of requests that may have internal dependencies. Direct submission usually requires unbounded maximumPoolSizes to avoid rejecting new tasks. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.

Unbounded queues. The use of unbounded queues (for example, blockingqueue with no predefined capacity) will cause new tasks to be added to the queue when all corePoolSize threads are busy. In this way, the created thread will not exceed the corePoolSize. (Therefore, the value of maximumPoolSize is invalid .) When each task is completely independent from other tasks, that is, task execution does not affect each other, it is suitable to use unbounded queues. For example, in a Web Page Server. This kind of queuing can be used to handle transient bursts of requests. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.

Bounded queue. When a limited number of maximumPoolSizes are used, a bounded Queue (such as ArrayBlockingQueue) helps prevent resource depletion, but may be difficult to adjust and control. The queue size and the maximum pool size may need to be compromised: using large queues and small pools can minimize CPU usage, operating system resources, and context switching overhead, but may cause manual throughput reduction. If the tasks are frequently congested (for example, if they are I/O boundaries), the system may schedule a longer time than you permit for more threads. Using a small queue usually requires a large pool size, and the CPU usage is high, but it may encounter unacceptable scheduling overhead, which will also reduce the throughput.

Rejected task

When the Executor has been disabled and the Executor uses the finite boundary for maximum thread and work queue capacity, and is saturated, execute (java. lang. runnable. In both cases, the execute method calls the RejectedExecutionHandler's RejectedExecutionHandler. rejectedExecution (java. lang. Runnable, java. util. concurrent. ThreadPoolExecutor) method. The following provides four predefined handler policies:

A. in the default ThreadPoolExecutor. AbortPolicy, A running RejectedExecutionException will be thrown if the handler is rejected.

B. In ThreadPoolExecutor. CallerRunsPolicy, the thread calls the execute itself that runs the task. This policy provides a simple feedback control mechanism to speed down the submission of new tasks.

C. In ThreadPoolExecutor. DiscardPolicy, tasks that cannot be executed will be deleted.

D. In ThreadPoolExecutor. DiscardOldestPolicy, if the execution program is not closed, the task in the Job Queue header will be deleted, and then the execution program will be retried (if the execution fails again, the process will be repeated ).

Defining and using other types of RejectedExecutionHandler classes is also possible, but you need to be very careful when doing so, especially when the policy is only used for a specific capacity or queuing policy.

Hook method
This class provides the rewritable beforeExecute (java. lang. thread, java. lang. runnable) and afterExecute (java. lang. runnable, java. lang. throwable) method. These two methods are called before and after each task is executed. They can be used to manipulate the execution environment; for example, reinitializing ThreadLocal, collecting statistics, or adding log entries. In addition, you can override the terminated () method to execute all the special processing that needs to be completed after the Executor is completely terminated.

If an exception is thrown by the hook or callback method, the Internal auxiliary thread will fail and terminate suddenly.

Queue Maintenance
The getQueue () method allows access to the work queue for monitoring and debugging purposes. It is strongly opposed to using this method for any other purpose. Remove (java. lang. Runnable) and purge () methods can be used to help with storage collection when a large number of queued tasks are canceled.

Author "walking in the rain"

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.