JAVA concurrent programming J. U. C learning summary, java concurrent programming j. u. c

Source: Internet
Author: User

JAVA concurrent programming J. U. C learning summary, java concurrent programming j. u. c
Preface

After learning J. U. C for a while, I plan to make a summary. I personally feel that the summary is very important. Otherwise, I always feel that the knowledge is scattered.

If you have any mistakes, please correct them and make common progress;

In addition, reprint please indicate the link, it is not easy to write an article, http://www.cnblogs.com/chenpi/p/5614290.html

The following table lists the main contents of J. U. C;

  • JSR 166 and J. U. C
  • Executor framework (thread pool, Callable, and Future)
  • AbstractQueuedSynchronizer (AQS Framework)
  • Locks & Condition (Locks and Condition variables)
  • Synchronizers)
  • Atomic Variables (Atomic variable)
  • BlockingQueue (blocking Queue)
  • Concurrent Collections (Concurrent container)
  • Fork/Join parallel computing framework
  • TimeUnit Enumeration
  • References
JSR 166 and J. U. C. What is JSR:

JSR, full name of Java Specification Requests, is a Java Specification proposal. It is mainly used to submit a formal request to JCP (Java Community Process) for adding a standardized technical Specification. Each JAVA version update has a corresponding JSR update. For example, in Java 8, the new Lambda expression corresponds to JSR 335, and the new date and time API correspond to JSR 310.

What is JSR 166:

Of course, this article focuses only on JSR 166, which is a standard proposal on Java concurrent programming. In JDK, this specification is developed by java. util. concurrent package implementation was introduced during JDK 5.0;

In addition, JDK 6 introduces Deques and Navigable collections, corresponding to JSR 166x. JDK 7 introduces the fork-join framework for parallel task execution, corresponding to JSR 166y.

What is J. U. C:

This is short for java. util. concurrent. For details about this package, see EDU. oswego. cs. dl. util. concurrent. It is an implementation of the JSR 166 Standard Specification;

Worship

So, who is the author of JSR 166 and J. U. C? That's right. It's a great god of Doug Lea. It's awesome. You can post a photo to worship it...

Executor framework (thread pool, Callable, Future) What is the Executor framework

Simply put, it is a framework for task execution and scheduling. The classes involved are shown in:

Among them, the top layer is the Executor interface. Its definition is very simple. An execute Method for executing tasks is as follows:

public interface Executor {    void execute(Runnable command);}

In addition, we can also see an Executors class, which is a tool class (similar to the Collections class of the Collection framework) for creatingExecutorService,ScheduledExecutorService,ThreadFactoryAndCallable object.

Advantages:

The task submission process is decoupled from the execution process. You only need to define the task submission and how to execute the task;

Typical steps:

Define a task (such as a Callable object), submit it to ExecutorService (such as a thread pool) for execution, get the Future object, and then call the get method of Future to wait for the execution result.

What is a task:

The class that implements the Callable interface or Runnable interface, and its instance can be submitted to ExecutorService for execution as a task;

The Callable task can return the execution result, but the Runnable task does not return the result;

What is a thread pool?

You can use the Executors tool class to create various types of thread pools, which are as follows:

For example (incomplete, only the process is demonstrated ):
ExecutorService executor = Executors. newCachedThreadPool (); // create a thread pool Task = new task (); // create a Callable Task Future <Integer> result = executor. submit (task); // submit the task to the thread pool for result execution. get (); // wait for the execution result; you can input the wait time parameter. If no result is returned within the specified time, it ends directly.
Supplement: Execution method of Batch Tasks

Method 1: first define the task set, then define the Future collection to store the execution results, execute the task, and finally traverse the Future collection to obtain the results;

  • Advantage: ordered results can be obtained in sequence;
  • Disadvantage: The execution results of completed tasks cannot be obtained in time;

Method 2: first define the task set, package ExecutorService through CompletionService, execute the task, and then call its take () method to retrieve the Future object

  • Advantage: Get the execution result of completed tasks in a timely manner
  • Disadvantage: results cannot be obtained in sequence.

In method 1, each Future object traversed from the set is not necessarily in the finished state, and calling the get () method will be blocked, therefore, even if the subsequent tasks are completed, the result cannot be obtained. In method 2, the implementation of CompletionService is to maintain a BlockingQueue that saves the Future object. Only when the Future object state ends, will be added to this Queue, so you can call take () to get the latest finished task results from the blocked Queue;

AbstractQueuedSynchronizer (AQS framework) What is AQS framework

The AQS framework is the basis for implementing locks and synchronization mechanisms in J. U. C. Its underlying layer is to implement thread blocking and wakeup by calling LockSupport. unpark () and LockSupport. park.

AbstractQueuedSynchronizer is an abstract class that maintains an int-type state attribute and a non-blocking, FIFO thread waiting queue. The state is modified with volatile, ensure the visibility between threads. The queue and the lock-free operation are implemented based on the spin lock and CAS. In addition, AQS can be divided into two modes: exclusive mode and shared mode, for example, ReentrantLock is implemented based on the exclusive mode, while CountDownLatch and CyclicBarrier are implemented based on the shared mode.

A simple example

Implementation of the lock method for unfair locks:

Final void lock () {// CAS operation. if the State is 0 (indicating that no other thread occupies the lock currently), set it to 1 if (compareAndSetState (0, 1) setExclusiveOwnerThread (Thread. currentThread (); else acquire (1 );}

First, try to obtain the lock directly regardless of the order (unfair embodiment). If the lock is successful, the access will be exclusively obtained;

If the lock fails to be obtained, call the acquire method of AQS. Within this method, the tryAcquire method is called to attempt to obtain the lock again and determine whether the lock can be re-entered. If the lock fails, then the current thread is suspended and added to the waiting queue;

For details, see the source code of the ReentrantLock. NonfairSync class and the AbstractQueuedSynchronizer class.

Locks & Condition (Locks and Condition variables)

Let's take a look at the main methods provided by the Lock interface as follows:

  • Lock () waiting to get the lock
  • LockInterruptibly () can interrupt and wait for the lock to be obtained. synchronized cannot implement the stoppedwait.
  • TryLock () attempts to obtain the lock and returns true or false immediately
  • TryLock (long time, TimeUnit unit) waits for the lock to be obtained within the specified time
  • Unlock () Release lock
  • NewCondition () returns a bound to thisLockOn the instanceConditionInstance

Concerning the implementation of the Lock interface, we mainly focus on the following two classes:

  • ReentrantLock
  • ReentrantReadWriteLock

ReentrantLock

A reentrant lock, also known as a recursive lock, means that a thread does not need to wait for the lock to be acquired again after obtaining the lock again. ReentrantLock is divided into fair locks and non-fair locks. Fair locks refer to waiting in the queue to obtain the locks strictly in the first-come-first-served order. Unfair locks attempt to obtain the locks directly each time they obtain the locks, failed to get, and then waited in the first-come-first-served order.

Note: ReentrantLock and synchronized are both reentrant locks.

ReentrantReadWriteLock

Re-entry into the write lock means that when there is no thread to perform write operations, multiple threads can perform read operations at the same time. When there is a thread to perform write operations, other read/write operations can only wait. That is, "Read-read can coexist, read-write cannot coexist, and write-write cannot coexist ".

When there are more reads than writes, the read/write locks can provide better concurrency and throughput than the exclusive locks.

Condition

A Condition object is created by a Lock Object. A Lock object can create multiple conditions. In fact, both the Lock and Condition are implemented based on AQS.

The Condition Object is mainly used for thread wait and wake-up. Before JDK 5, the thread wait wake-up is implemented using the wait/notify/yyall method of the Object, which is not very convenient to use;

After JDK 5, the J. U. C package provides Condition, where:

Condition. await corresponds to Object. wait;

Condition. signal corresponds to Object. equaly;

Condition. signalAll corresponds to Object. policyall;

One obvious advantage of using a Condition object is that a lock can create multiple Condition objects. We can assign a Condition to a certain thread and then wake up a thread of a specific class.

Synchronizers)

The synchronizers in J. U. C are mainly used to assist thread synchronization. There are four types:

Locking CountDownLatch

Blocking is mainly used to let a main thread wait for a group of events to continue execution. The event here is actually the countDown method of the CountDownLatch object. Note that other threads continue to execute the countDown method after calling it, as shown in:

Inside CountDownLatch, a counter is contained. It is initialized as an integer (number of events) at the beginning. After an event occurs, the countDown method is called, and the counter is reduced by 1, await is used to continue executing the current thread after the counter is 0;

For example, the main TA thread will wait until the count cnt = 0 until execution continues,

You can refer to the previous article, as shown in the following link, which contains a blocking demo.

Http://www.cnblogs.com/chenpi/p/5358579.html

Barrier

Barrier is mainly used to wait for other threads and will block their current thread. All threads must arrive at the barrier position at the same time before they can continue to run. In addition, when all threads reach the barrier, another preset thread can be triggered, as shown in:

In the middle, Every time T1, T2, and T3 call await, the count is reduced, and when they call the await method, if the count is not 0, their own threads will be blocked;

In addition, the TA thread starts execution only when all threads reach the barrier (the count is 0;

Refer to the previous article, as shown in the following link. There is a fence demo.

Http://www.cnblogs.com/chenpi/p/5358579.html

Semaphores Semaphore

Semaphores are mainly used to control the number of threads used to access resources. They are often used to implement resource pools, such as database connection pools and thread pools...

In Semaphore, The acquire method is used to obtain resources. If yes, continue to execute (remember to release resources after use). If no resources exist, it will be blocked until other threads call the release method to release resources;

Refer to the previous article, as shown in the following link, which contains a demo of the semaphore.

Http://www.cnblogs.com/chenpi/p/5358579.html

Switch Exchanger

Switches are mainly used for data exchange between threads;

When both threads reach a common synchronization point (when both threads are executed to exchanger. exchange), data exchange occurs; otherwise, data will wait until other threads arrive;

Atomic Variables (Atomic variable)

Atomic variables are mainly used to facilitate programmers to perform atomic operations without locks in multi-threaded environments;

The atomic class is a packaging Class Based on the Unsafe implementation, and the core operation is the CAS atomic operation. The so-called CAS operation is compare and swap, compare the expected value with the current variable value (compare). If the values are equal, replace the current variable with the new value (swap). Otherwise, no operation is performed; we can extract the source code of AtomicInteger as follows:

    public final boolean compareAndSet(int expect, int update) {        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);    }

In the compareAndSwapInt method, valueOffset is the memory address, CT is the expected value, and update is the updated value. If the value at the valueOffset address is equal to the expected value, the value at the valueOffset address is updated to the update value. PS: The Modern CPU has widely supported CAS commands;

There are four atomic update Methods in Java:

  • Update basic types in atomic mode; AtomicInteger, AtomicLong, etc.
  • Update arrays in atomic mode; AtomicIntegerArray, AtomicLongArray, etc.
  • Update Reference in atomic mode; AtomicReference, AtomicReferenceFieldUpdater...
  • Update fields in atomic mode; AtomicIntegerFieldUpdater, AtomicStampedReference (solves the ABA problem of CAS )...

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.