Java Concurrent Programming Combat (V)----task execution

Source: Internet
Author: User

One, perform tasks in the thread

1, the lack of unlimited creation threads:

    • The cost of the thread life cycle is very high. The process of creating threads takes time, which delays the processing of requests and requires some secondary operations from the JVM and the operating system.
    • Resource consumption. If the number of threads that can run is more than the number of available processors, then some threads are idle and consume a lot of memory, and if a large number of threads compete on the CPU, they also incur additional performance costs.
    • Stability. There is a threshold on the number of threads that can be created, which varies depending on the platform and is subject to several factors, including the startup parameters of the JVM, the size of the requested stack in the thread constructor, and the threading limitations of the underlying operating system. If this limit is exceeded, there is likely to be an oom exception.

In a certain range, increasing the number of threads can increase the throughput of the system, but if this range is exceeded, creating more threads will only slow down the execution of the program, and if too many threads are created, the entire system may crash. To avoid this danger, you should limit the number of threads that an application can create, and test the application thoroughly to ensure that the number of threads reaches a limit and the program does not run out of resources.

2,executor Frame

The problem with serial execution is its poor responsiveness and throughput, and the issue of "Assigning a thread to every task" is the complexity of resource management. So with the thread pool, the thread pool simplifies the management of threads, and Java.util.concurrent provides a flexible thread pool as part of the executor framework. In the Java class Library, the task executes not thread, but executor:

 Public Interface Executor {    void  execute (Runnable command);}

1, executor-based Web server

classTaskexecutorwebserver {Private Static Final intNthread = 100; Private Static FinalExecutor exe =Executors.newfixedthreadpool (Nthread);  Public Static voidMain (string[] args) {serversocket socket=NewServerSocket (80);  while(true) {            FinalSocket connection =socket.accept (); Runnable Task=NewRunnable () { Public voidrun () {handlerequest (connection);            }            };        Exec.execute (Task); }    }}

In Taskexecutionwebserver, the submission of a request processing task is decoupled from the actual execution of the task by using executor.

It is also easy to modify the previous example to Threadpertaskwebserver behavior, using only one executor to create a new thread for each request.

 Public class Implements Executor {    publicvoid  execute (Runnable r) {        new  Thread (R) . Start ();}    }

You can also write a executor that makes threadpertaskexecutor behave like a single-threaded behavior:

 Public class Implements Executor {    publicvoid  execute (Runnable r) {        R.run ()}    }

***************************************************

Whenever you see the following form of code and want to get a more flexible execution strategy, consider using executor instead of thread:

New Thread (runnable). Start ();

***************************************************

3, Thread pool

A thread pool is a resource pool that manages the same set of worker threads. The thread pool is closely related to the work queue, where all the tasks awaiting execution are saved in the work queue. The task for a worker thread is simple: get a task from the work queue, execute the task, and then return to the thread pool and wait for the next task.

"Performing tasks in thread pooling" has more advantages than "assigning one thread to each task". By reusing existing threads instead of creating new ones, you can reduce the overhead of thread creation and destruction. Another benefit is that when a request arrives, it is no longer delayed because it waits for thread creation, and it improves responsiveness. By resizing the thread pool appropriately, you can create enough threads to keep the processor busy, while also preventing excessive threads from competing with each other for resources and draining the application out of memory.

The class library provides a flexible thread pool and some useful default configurations. You can create a thread pool by calling one of the static factory methods in executors:

    • Newfixedthreadpool: Creates a fixed-length thread pool that creates a thread every time a task is committed, until the maximum number of thread pools is reached, and the size of the thread pool will no longer change.
    • Newcachedthreadpool: Create a cacheable thread pool that will reclaim idle threads if the current size of the thread pool exceeds the processing requirements, and when the demand increases, you can add new threads that have no limit on the size of the thread pool.
    • Newsinglethreadexecutor: is a single-threaded executor that creates a single worker thread to perform a task, and if this thread ends abnormally, another thread is created instead. It ensures serial execution according to the order of the tasks in the queue.
    • Newscheduledthreadpool: Creates a fixed-length thread pool and performs tasks in a deferred or timed manner, similar to a timer.

The life cycle of 4,executor

Because executor executes the task asynchronously, the state of the previously committed task is not immediately visible at any point in time. Some tasks may be completed, some may be running, and other tasks may wait in the queue for execution. When the application is closed, it may take a gentle approach (complete all the tasks that have been started, and no longer accept any new tasks), or it may be rude (all of them are switched off directly). Executor is considered an application-provided service, so they are also closed and returned to the application with the state of the affected task in the shutdown operation.

To solve the life cycle problem of performing tasks, the Executorservice interface extends the executor and adds some methods for life cycle management:

 Public Interface extends Executor {    void  shutdown ();    List<Runnable> shutdownnow ();     Boolean IsShutDown ();     Boolean isterminated ();     boolean awaittermination (longthrows  interruptedexception;    ...}

The Exectuorservice life cycle has three states:

Java Concurrent Programming Combat (V)----task execution

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.