Java-concurrency-advanced concurrent object 1, java-concurrent object

Source: Internet
Author: User

Java-concurrency-advanced concurrent object 1, java-concurrent object

Previously speaking, thread objects are very basic APIs on the java platform. They are used to process some basic tasks. For some complex and advanced jobs, advanced concurrent objects are required, especially for today's applications, we need to make full use of the performance of the current multi-core multi-processor system.

The following content includes some high concurrency features of the java platform starting from java 5. Most of these features are implemented in the java. util. concurrent package, and the java Collection framework also has a new concurrent data structure.

Lock Object

The synchronization code depends on a simple re-entry lock, which is easy to use but has many limitations,Java. util. concurrent. locks supports many advanced Lock usage. Here we will focus on the most basic interface Lock.

The Lock object function is similar to the implicit Lock used by the synchronization code. The similarity is that a Lock object can only be owned by one thread at a time, and the Lock object also has the wait/notify mechanism, although they are related to the Condition object.

The biggest advantage of a Lock object over an implicit Lock is that it can retrieve the Lock request. Its tryLock method can retrieve the request if the requested Lock cannot be obtained or if it is specified before the timeout, if another thread sends an interrupt signal before the request lockThe lockInterruptibly method revokes the request.

Correct use of the lock object can avoid deadlock. That is, if a thread needs to synchronize two objects, ensure that the lock of the two objects is obtained at the same time. The typical usage of tryLock is as follows:

Lock lock = ...; // The creation expression if (lock. tryLock () {try {// operation if the lock is successfully obtained} finally {// release the lock after the operation. unlock () ;}} else {// If the lock fails to be obtained}
Performer

In all previous examples, there is a close relationship with the work of a new Thread, such as the Runnable object defined in the class and the Thread object defined itself, however, in large programs, thread management and creation are generally separated from other parts of the program, and the objects encapsulated with these functions are called executors. The executors are divided into three parts as follows:

  • Executor interface -- Define three executor object interface types
  • Thread Pool-Implementation of the most common class of executors
  • Fork/Join framework that makes full use of multi-processor performance (introduced by JDK7)
Executer Interface

The java. util. concurrent package defines three executor interfaces:

  • Executor-a simple interface that supports starting a new task
  • ExecutorService-sub-interface of Executor, which adds the features to help manage the lifecycle, including the lifecycle of individual tasks and executors.
  • ScheduledExecutorService -- ExecutorService sub-interface, supporting and/or periodic task execution

Generally, the types of variables that reference the performer object are declared as the above three interface types, rather than the types of classes that implement interfaces.

The Executor interface provides a single method, execute, which is designed as an alternative to the creation of a common thread object, such:

// Replace the following Thread creation method (new Thread (r). start (); // With e.exe cute (r); // note that e is the Executor object with the created number

The definition of method execute is not very clear. After a low-level method creates a new thread object, it immediately starts execution. The Executor object may also be executed immediately according to the specific implementation, however, it is more often to use existing threads to run the r in the example, or put the r in the queue for running (as described in the thread pool below ).

The executor implementation class in the java. util. concurrent package is designed to provide more advanced ExecutorService and ScheduledExecutorServiceOf course, this interface is also applicable to the basic Executor interface.

The ExecutorService interface adds a similar but more powerful submit method to the execute method. Just like the execute method, the submit method receives the Runnable object as a parameter, you can also receive a Callable object that allows the task to return a value. The submit method returns a Future object, which can retrieve the value returned by the Callable object and manage the status of the Callable and Runnable tasks.

The ExecutorService interface also provides methods to support submission of a large number of Callable object sets, and finally many methods to manage the termination of executors. If you need to terminate immediately, you need to correctly handle the interruption.

The ScheduledExecutorService interface not only inherits the features of ExecutorService, but also supplements the schedule method. This method can delay the execution of Runnable and Callable objects. In addition, the scheduleAtFixedRate and scheduleWithFixedDelay Methods specify the repetition and.

Thread Pool

Most java. util. the implementation classes of executor interfaces in the concurrent package all use the thread pool, which is composed of multiple worker threads, which exist in the Runnable and Callable tasks they execute respectively.

The use of the thread pool minimizes the cost of thread creation, thread objects require a large amount of memory, and in large programs, the allocation and unallocation of thread objects will incur a large amount of memory management expenses.

There is a common thread pool called a fixed thread pool, which always has a specified number of threads running. If a thread is terminated for some reason and the thread pool is still running, the thread pool automatically replaces the new thread. When the number of excessive threads of a task is active, the task is submitted to the thread pool through an internal queue.

An important advantage of a fixed thread pool is that applications can use it to cleverly reduce load. For example, in a web server application, each HTTP request is processed by an independent thread, if the program simply creates a new thread for a new HTTP request, as the number of requests increases, the system will soon have no resources to create more threads, the program may fail to run. Only when the number of threads created is limited and processed in sequence by queue can the program run effectively.

To create an Executor using a fixed thread pool, call the newFixedThreadPool factory method of java. util. concurrent. Executor. This class also provides the following factory methods:

  • The newCatchedThreadPool method creates an executor with a scalable thread pool. This executor applies to programs that need to execute short tasks.
  • NewSingleThreadExecutor

When the above factory methods cannot meet the requirements, you can createJava. util. concurrent. ThreadPoolExecutor orJava. util. concurrent. ScheduledThreadPoolExecutor instance to provide more functions.  

Fork/Join

The Fork/Join framework isExecutorServiceThe implementation of interfaces helps you make full use of the performance of the multi-processor. It is designed for Recursive tasks, the purpose is to use all available processing resources to enhance program performance.

Just like other ExecutorService interface implementation proposals, the fork/join Framework assigns tasks to the worker threads in the thread pool. The fork/join framework is different from its "Work theft" algorithm, threads that have completed the task can steal the task from other busy threads.

The fork/join framework is centered on the ForkJoinPool class, which is an extension of the AbstractExecutorService class. The ForkJoinPool class implements the core work stealing algorithm and can execute the ForkJoinTask process.

The basic usage of fork/join is to first define a class that inherits the ForkJoinTask class or the ForkJoinTask subclass for processing part of the work. After defining the class, instantiate the class and pass it as a parameter.ForkJoinPoolInstance invoke method.

Java se has some common features that have been implemented using the fork/join framework, such as java of java 8. util. the parallelSort method of the Arrays class. This method is similar to the sort method. However, using the fork/join framework, parallel sorting for large Arrays is faster than serial sorting in a multi-processor system. Another implementation that utilizes the fork/join framework is some methods in the java. util. streams package.

  

 

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.