The use of thread pool for Java concurrent programming

Source: Internet
Author: User

Implicit coupling between task and execution strategy

The executor framework decouples the submission of a task from the execution strategy of the task (that is, to be independent). Although the Executor framework provides considerable flexibility for formulating and modifying execution strategies, not all tasks can be applied to all execution strategies

Like what:

Dependency Tasks

For example, depending on the execution timing, execution results, or other effects, the task has implicit dependencies. These execution strategies must be carefully maintained at this time to avoid active problems (deadlocks and other problems that cause difficulties in execution)

Tasks that use the thread closure mechanism

Single-threaded executor can make a stronger commitment to concurrency than the thread pool, which ensures that tasks do not execute concurrently.

tasks that are sensitive to response time

such as GUI tasks. If you commit a long-running task to a single-threaded executor. Or to commit multiple, long-running tasks to a thread pool that contains only a small number of threads, this executor will be less responsive.

tasks that use threadlocal

Threadlocal enables each thread to have a private version of a variable, however. These threads are freely reused as long as the conditions allow executor to. In a standard executor, a space thread is reclaimed when the demand for execution is low, and a new thread is added when the demand increases, and if an unchecked exception is recruited from the task, a new thread is used to replace the problematic thread. The use of threadlocal in threads in the thread pool is meaningful only if the lifetime of the thread-local value is limited to the life cycle of the task, and the thread in the online pool should not use threadlocal to pass values between tasks.




Finally, the performance of the thread pool is best achieved only if the tasks are of the same type and are independent of each other. If you put a task with a large running time in the same thread pool, it will cause blocking unless the thread pool is large enough. Typical web-based server applications, such as Web servers, mail servers, and file servers, are of the same type and are independent of each other's requests.


Remember that your execution strategy is written to the document, and future maintainers will not compromise security and activity by using the wrong execution strategy.


Thread Starvation Deadlock

If it is a single thread of executor. If two tasks are submitted and the two tasks depend on each other's execution results, a deadlock is created.

Give me a chestnut:

Import Java.lang.processbuilder.redirect;import Java.util.concurrent.callable;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.Future; public class Threaddeadlock {Executorservice exec = Executors.newsinglethreadexecutor ();p ublic static void Main (string[ ] args) {try {threaddeadlock TDL = new Threaddeadlock (); System.out.println (Tdl.new readerpagetask (). Call ());} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public class Readerpagetask implements callable<string> {@Overridepublic String call () throws Exception {//TODO Aut O-generated method stubfuture<string> Header, Footer;header = Exec.submit (New Loadfiletask ("header.html")); Footer = Exec.submit (new Loadfiletask ("footer.html")); String page = "bodyyyyyyyyyyyyyyy";//deadlock will occur because the task is waiting for the result of the subtask return Header.get () + page + footer.get ();}} public class Loadfiletask implements callable<string> {public loadfiletask (String filepath) {super ();//Todo auto-generated constructor stub} @Overridepublic String Call () throws Exception {//TODO auto-generated method Stubret Urn "SDF";}}}
The chestnut above can be used to calculate the result. But it's a lot slower. belongs to the thread starvation deadlock.
Deadlock is not necessarily "dead", look at the definition of deadlock.

Specification definition for deadlocks: Each process in the collection waits for an event that can only be raised by another process in this collection, then the group process is deadlocked.

In addition to the explicit restrictions on the size of the thread pool, there are many deadlocks due to external resource constraints, such as a JDBC limit of 10 connections, so each thread needs a connection, and 10 threads are already running in the thread pool, so the next thread is already in the threads pool. However, because the connection to the database cannot be made blocked.


long-running tasks

If the task is blocked for too long, the thread pool's responsiveness can get worse even without a deadlock. Java has long prepared the way to solve the problem. Most blocking methods have limited-time versions and unlimited versions in Java libraries, such as Thread.join.Blockingqueue.put.CountDownLatch.await and Select.select. If you wait for a timeout, you can identify the task as failed, then abort the task or put the task back in the queue, or even add a counter. If a few failures remain so then stop it again. If the line Cheng is always full of blocked tasks, it may also indicate that the thread pool is too small.


The use of thread pool for Java concurrent programming

Related Article

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.