Java Multithreading: Currenthashmap

Source: Internet
Author: User
Tags volatile

I. Backgroundthreads are scarce resources that, if created without restrictions, not only consume system resources, but also reduce system stability, using a thread pool to distribute, tune, and monitor threads uniformly, with the following benefits:First: Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the threads that have been created. Second: Improve response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created. Third: Improve the manageability of threads.  second, the structure of the thread poolThird, executorsused to create a thread poolnewfixedthreadpool (fixed size thread pool)   Initializes a thread pool with a specified number of threads, where corepoolsize = = Maximumpoolsize, using Linkedblockingquene as the blocking queue, but does not release the thread when the thread pool has no executable task.  
 Public Static Executorservice newfixedthreadpool (int  nthreads) {        returnnew0L, Timeunit.milliseconds,new linkedblockingqueue<runnable>());  }
 newcachedthreadpool (no boundary pool, automatic thread recovery is possible)1. Initialize a thread pool that can cache threads, default cache 60s, use Synchronousqueue as blocking queue;2. Unlike the thread pool created by Newfixedthreadpool, Newcachedthreadpool automatically frees thread resources when there is no task execution, when the thread is idle for more than KeepAliveTime, and when a new task is submitted, If there is no idle thread, creating a new thread to perform the task will result in a certain amount of system overhead;therefore, when using this thread pool, be careful to control the number of concurrent tasks, otherwise creating a large number of threads can cause serious performance problems.  
 Public Static Executorservice Newcachedthreadpool () {          returnnew threadpoolexecutor (0 60L New Synchronousqueue<runnable>());      
  newsinglethreadexecutor (single background thread)   there is only one thread in the initialized thread pool, and if the thread ends abnormally, a new thread is recreated to continue the task, and the only thread can guarantee the order in which the submitted tasks are executed, using Linkedblockingqueue as the blocking queue internally.  
 Public Static Executorservice Newsinglethreadexecutor () {          returnnew  Finalizabledelegatedexecutorservice              (new threadpoolexecutor (110L  New linkedblockingqueue<runnable>()));      
  Newscheduledthreadpoolcreates a fixed-length thread pool and performs tasks in a deferred or timed manner.  with the source code of the thread pool creation method as configured above, we can find:1> except that Cachedthreadpool uses a buffer queue that directly submits the policy, the remaining two are in the unbounded buffer queueThe 2> three thread pool uses the same Threadpoolexecutor construction method, using the default Threadfactory and handler:
Private StaticFinal Rejectedexecutionhandler DefaultHandler =NewAbortPolicy ();  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, timeunit unit, Blockingqueue<Runnable>workQueue) {       This(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Executors.defaultthreadfactory (), Defaulthand  LER); }
submit the task with submit (), close the thread pool with shutdown (). Iv. executorservice Task Cycle Management interfaceexecutor implementations typically create threads to perform tasks, but when performing tasks asynchronously, because the state of the previously committed task is not immediately visible, the affected task state needs to be fed back to the application if it is to close the application. to address the life cycle of service execution, executor extends the Eecutorservice interface and adds some methods for life cycle management. as follows:
 Public Interface Executorservice extends Executor {      void  shutdown ();      List<Runnable> shutdownnow ();      Boolean IsShutDown ();      Boolean isterminated ();      Boolean awaittermination (long  timeout, timeunit unit) throws interruptedexception;       // omit partial method   }
Wu, Threadpoolexecutorthe main workflow of the thread pool is as follows:the key variables defined in the class are as follows:
  1.PrivateFinal blockingqueue<runnable> WorkQueue;//Blocking Queues  2.PrivateFinal Reentrantlock Mainlock =NewReentrantlock ();//Mutual exclusion Lock  3.PrivateFinal hashset<worker> workers =NewHashset<worker> ();//The thread collection. A worker corresponds to a thread  4.PrivateFinal Condition termination = Mainlock.newcondition ();//Termination Conditions  5.Private intLargestpoolsize;//the maximum number of threads in a thread pool that has ever reached the limit.   6.Private LongCompletedtaskcount;//number of completed tasks  7.Private volatileThreadfactory threadfactory;//the Threadfactory object that is used to create the thread.   8.Private volatileRejectedexecutionhandler handler;//processing handle for deny policy  9.Private volatile LongKeepAliveTime;//the thread pool maintains idle time allowed by threads  Ten.Private volatileBoolean allowcorethreadtimeout;  One.Private volatile intCorepoolsize;//The thread pool maintains the minimum number of threads, even if it is idle   A.Private volatile intMaximumpoolsize;//maximum number of threads maintained by the thread pool

There are several important rules that need to be explained:1> corepoolsize and MaximumpoolsizeThe thread pool automatically adjusts the pool size based on the boundaries set by Corepoolsize and Maximumpoolsize, when new tasks are committed in method execute ():
    • If the number of threads in the current thread pool is less than corepoolsize, then each task will create a thread to perform the task;
    • If the number of threads in the current thread pool is >=corepoolsize, each task will attempt to add it to the task cache queue, and if added succeeds, the task waits for the idle thread to take it out and creates a new thread to process the request when the queue is full;
    • If the number of threads in the current thread pool reaches maximumpoolsize, that is, the queue is full, the new request is processed through the task deny policy specified by handler;
    • If the number of threads in the thread pool is greater than corepoolsize, if a thread is idle longer than KeepAliveTime, the thread is terminated until the number of threads in the thread pool is not greater than corepoolsize;
 In other words, the priority of the processing task is:
    • 1. Core thread corepoolsize > task queue workqueue > Max thread maximumpoolsize, if all three are full, use handler to handle the rejected task.
    • 2. When the number of threads in the pool is greater than corepoolsize, the extra thread waits for KeepAliveTime for a long time and destroys itself if no request can be processed.
 2> WorkQueueThe buffer queue used by the thread pool, the length of which determines the maximum number of buffers that can be buffered, and the buffer queue has three common policies:1) Submit directly. Synchronousqueue, which directly submit the task to the thread execution without saving them. Here, if there is no thread available to run the task immediately, attempting to join the task to the queue will fail, and a new thread will be constructed. This policy avoids locking when processing a set of requests that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. 2) unbounded queue. The use of unbounded queues will cause all corepoolsize threads to be busy while the newly task waits in the queue. This way, the created thread will not exceed corepoolsize. (therefore, the value of the maximumpoolsize is not valid.) When each task is completely independent of other tasks, that is, task execution is not affected, it is appropriate to use unbounded queues;3) bounded queue. When using limited maximumpoolsizes, bounded queues (such as arrayblockingqueue) help prevent resource exhaustion, but may be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: using large queues and small pools minimizes CPU usage, operating system resources, and context switching overhead, but can result in artificially reduced throughput. If tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you permit. Using small queues typically requires a large pool size, high CPU utilization, but may encounter unacceptable scheduling overhead, which also reduces throughput.3>threadfactoryCreate a new thread using Threadfactory. By providing different threadfactory, you can change the name of the thread, the thread group, the priority, the daemon state, and so on. If threadfactory fails to create a thread when returning null from Newthread, the executor continues to run, but cannot perform any tasks.
    1. Public interface Threadfactory {
    2. Thread Newthread (Runnable R);
    3. }
The Threadfactory object in the construction method is returned by Executors.defaultthreadfactory (). 4>rejectedexecutionhandlerwhen executor is closed (that is, after the Executorservice.shutdown () method is executed), and executor uses a limited boundary for the maximum thread and work queue capacity, and is already saturated, the method execute () The new task that is submitted in will be rejected.in the above case, the Execute method calls the Rejectedexecutionhandler.rejectedexecution () method. The following four predefined handler policies are available:1) AbortPolicy directly throws abnormal rejectedexecutionexception;2) Callerrunspolicy perform tasks with the caller's thread3) Discardpolicy tasks that cannot be performed will be deleted;4) Discardoldestpolicy If the execution program has not been closed, the task in the head of the work queue is deleted, and then the program is retried (repeat this process if it fails again). 5>keepalivetimeThe time at which the thread is idle, that is, when the thread does not have a task to execute, the time to survive; By default, the parameter is only useful if the number of threads is greater than corepoolsize ;vi. closure of the thread poolThe thread pool is closed by invoking the shutdown or Shutdownnow method of the thread pool, but they are implemented differently, shutdown simply sets the state of the thread pool to the shutdown state, and then interrupts all threads that are not performing the task. Shutdownnow is traversing a worker thread in the thread pool and then calling the thread's interrupt method one at a time, so a task that cannot respond to the interrupt may never be terminated. Shutdownnow first sets the status of the thread pool to stop, and then tries to stop all threads that are executing or pausing the task, and returns a list of waiting tasks to be performed. The IsShutDown method returns True whenever one of the two closing methods is called. The call to the Isterminaed method returns True when all tasks have been closed to indicate that the thread pool was successfully closed. As to which method we should call to close the thread pool, it should be determined by the task attributes that are committed to the thread pool, usually called shutdown to close the thread pool, and shutdownnow can be called if the task does not have to be completed.  vii. configuration of thread poolThe analysis can be made from the following angles:1. Nature of tasks: CPU-intensive tasks, IO-intensive tasks, and hybrid tasks. 2. Priority of tasks: high, medium and low. 3. Task execution time: long, medium and short. 4. Dependencies on tasks: whether to rely on other system resources, such as database connections. CPU-intensive tasks are configured with as few threads as possible, such as configuring thread pooling for ncpu+1 threads. IO-intensive tasks are configured as many threads as possible, such as 2*NCPU, due to the need to wait for IO operations and the thread is not always performing the task. A mixed-type task, if it can be split, splits it into a CPU-intensive task and an IO-intensive task, as long as the time difference between the two tasks is not too large, then the throughput performed after the decomposition is higher than the serial execution throughput rate, if the two task execution time difference is too large, It is not necessary to decompose. we can get the number of CPUs for the current device through the Runtime.getruntime (). Availableprocessors () method. tasks with different priority levels can be handled using the priority queue Priorityblockingqueue. It allows high-priority tasks to be executed first, and it is important to note that low-priority tasks may never be executed if a task with a high priority is committed to the queue. tasks with different execution times can be handled by different sizes of thread pools, or priority queues can be used to perform tasks that have a short execution time. a task that relies on the database connection pool, because the thread submits the SQL and waits for the database to return the results, and the longer the CPU idle time waits, the greater the number of threads should be, so that the CPU can be better utilized. The proposed use of bounded queues, the bounded queue can increase the stability of the system and early warning ability, can be set to a larger point

Java Multithreading: Currenthashmap

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.