Introduction to the Java 8 concurrency Toolkit
Transferred from: http://www.toutiao.com/a6399027925228077313/
The Java 8 concurrency Toolkit consists of 3 packages, java.util.concurrent, java.util.concurrent.atomic, and Java.util.concurrent.locks, which provide a large number of interfaces for concurrency, classes , atomic operation class, lock related class. With the java.util.concurrent package, complex concurrency operations can be implemented with great ease. The Java.util.concurrent package mainly contains the following content, which will be described in detail below:
Blocking queues: Implementations of a variety of blocking queues that can block consumer or producer-related threads when the queue is empty or full.
Concurrent containers: Container types for concurrent scenarios, typically without locking.
Thread pool: Creates a single-threaded, fixed-size, or cacheable thread pool that supports recurring tasks and also enables the return of asynchronous tasks.
Lock: The lock used for concurrent synchronization;
Atomic type: The type of data used to implement atomic operations, including Atomicboolean, Atomicinteger, Atomiclong, atomicreference, etc.
Concurrency tool: A class for concurrent scenarios that can control synchronization, waiting for concurrent threads.
Blocking Queue Blockingqueue
In Blockingqueue, the producer can continuously insert new elements into the queue until the queue is full, the producer thread is blocked after the queue is full, and the consumer can continue to fetch elements from the queue until the queue is empty and the queue is empty and the consumer thread is blocked.
Blockingqueue provides four types of operation methods that behave differently when the operation cannot be performed immediately.
|
Throw exception |
Return special values |
Blocking |
Timeout returned |
| Insert |
Add (o) |
Offer (O) |
Put (o) |
Offer (o, timeout, timeunit) |
| Delete |
Remove (o) |
Poll |
Take |
Poll (timeout, timeunit) |
| Check |
Element |
Peek |
|
|
Java 8 provides several types of blockingqueue implementation classes,
Arrayblockingqueue: Bounded blocking queue based on array implementation, cannot modify the size of queue after creation;
Linkedblockingqueue: A bounded blocking queue based on a linked list, with a default size of Integer.max_value, with good throughput but poor predictability.
Priorityblockingqueue: Unbounded blocking queue with priority, NULL is not allowed, all elements must be comparable (i.e. implement comparable interface).
Synchronousqueue: Only one element of the synchronization queue. If an element in the queue is inserted, it will be blocked until the element in the queue is taken away by another thread.
Delayqueue: Unbounded blocking queue, each element has a delay time before the element is released after the delay time.
Blocking the double-ended queue Blockingdueue
Dueue is the abbreviation for "Double Ended Queue". Producers and consumers can insert and delete operations at both ends of the queue.
There are four types of operations available in the head, with different performance when the operation cannot be performed immediately.
|
Throw exception |
Return special values |
Blocking |
Timeout returned |
| Insert |
AddFirst (o) |
Offerfirst (o) |
Putfirst (o) |
Offerfirst (o, timeout, timeunit) |
| Delete |
Removefirst (o) |
Pollfirst (o) |
Takefirst (o) |
Pollfirst (timeout, timeunit) |
| Check |
GetFirst (o) |
Peekfirst (o) |
|
|
There are four types of operations available at the trailer, with different performance when the operation cannot be performed immediately.
|
Throw exception |
Return special values |
Blocking |
Timeout returned |
| Insert |
AddLast (o) |
Offerlast (o) |
Putlast (o) |
Offerlast (o, timeout, timeunit) |
| Delete |
Removelast (o) |
Polllast (o) |
Takelast (o) |
Polllast (timeout, timeunit) |
| Check |
GetLast (o) |
Peeklast (o) |
|
|
Java 8 provides only one type of blockingdueue implementation class,
Linkedblockingdeque: A bounded blocking queue based on a doubly linked list, with a default size of Integer.max_value, with good throughput but poor predictability.
Blocking the transfer queue Transferqueue
The Transferqueue interface inherits the Blockingqueue interface, so it has all the methods of the Blockingqueue interface and adds some methods. The methods and functions are as follows:
Trytransfer (E): If there is currently a consumer thread waiting to be acquired, the method immediately transfers E and returns True, False if not present, but does not insert E into the queue. This method does not block the current thread, either quickly returns true, or quickly returns false.
Transfer (E): If a consumer thread is currently waiting to be acquired, the E is immediately handed over, otherwise the element e is inserted at the end of the queue, and the current thread goes into a blocking state until a consumer thread takes the element away.
Trytransfer (e E, long timeout, timeunit unit): If there is currently a consumer thread waiting to be acquired, it will be transferred to it immediately; Otherwise, the element e is inserted at the end of the queue and waits for consumption by the consumer thread. If the element e cannot be fetched by the consumer thread for the specified time, then false is returned, and the element is removed from the queue.
Java 8 provides a list-based implementation class LinkedTransferQueue.
Concurrent containers
The toolkit provides a queue of concurrent implementation classes Concurrentlinkedqueue and Concurrentlinkeddeque, both of which are unbounded non-blocking thread-safe queues.
The Concurrentmap interface inherits the common map interface, providing thread-safe and atomic manipulation features. Java 8 provides the implementation class CONCURRENTHASHMAP,CONCURRENTHASHMAP does not lock the entire map, locking only the parts that need to be written, so concurrency performance is much higher than Hashtable.
The Concurrentnavigablemap interface inherits the Concurrentmap and Navigablemap interfaces, supports concurrent access Navigablemap, and allows the child map to have concurrent access capabilities. Navigablemap is an extended sortedmap with a navigation method that returns the closest match for a given search target.
Java 8 provides implementation class Concurrentskiplistmap, and does not use lock to guarantee concurrent access and modification of threads, but instead uses non-blocking algorithms to guarantee concurrent access, while high concurrency has a distinct advantage over treemap.
The toolkit provides Navigableset's concurrency implementation class Concurrentskiplistset, which is a thread-safe, ordered collection for high concurrency scenarios, implemented through CONCURRENTSKIPLISTMAP.
The toolkit provides two write-time replication containers, copyonwritearraylist and Copyonwritearrayset. Copy-on-write technology is an optimization strategy where multiple threads can access the same data concurrently, and then copy and modify the thread thread as it is being modified. In a Linux system, after the fork process, the child process shares the data with the parent process and needs to be modified before it can be copied with its own copy. In Java, when the copy container modifies the data, the reference of the original container is pointed to the new container to realize the read and write separation, and no lock is needed in the concurrent read and write. Copy-on-write containers are suitable for scenarios where there is less read, more memory is used during replication, and eventual consistency is guaranteed, but no instantaneous consistency can be guaranteed.
Thread pool
The executor interface in the toolkit defines the basic function of the executor, the Execute method, receiving the Runnable object parameters and performing the operations in Runnable.
The Executorservice interface inherits the executor interface and adds definitions for the executor service, such as closing, closing immediately, checking for shutdown, waiting for termination, committing tasks with return values, batch submitting tasks, and so on. By executors's factory method to obtain the specific implementation of Executorservice, currently executors can return the following implementation types:
Fixedthreadpool: A fixed-size thread pool that is created with a specified size;
Workstealingpool: A thread pool with multiple task queues (to reduce the number of connections);
Singlethreadexecutor: Single-threaded actuator, as the name implies only one thread to perform the task;
Cachedthreadpool: Create threads as needed, can reuse existing threads to perform tasks;
Singlethreadscheduledexecutor: The creation of a single worker thread or a recurring single-threaded actuator based on a time plan delay;
Scheduledthreadpool: Ability to postpone tasks or perform tasks in a fixed cycle.
If you want to get the return value of the task after the task is completed, you can call the Submit method to pass in the callable task and see whether the task execution is completed by the returned future object and get the return value.
Threading Fork and Merge
Forkjoinpool allows us to easily split the task into smaller tasks, and these split tasks will be presented to Forkjoinpool. The task can continue to be split into smaller subtasks as long as it can be split. The branching and merging principle consists of two recursive steps. The two steps are fork steps and merge steps, respectively.
A task that uses a fork and merge principle can fork (split) itself into smaller subtasks, which can be executed concurrently. As shown in the following:
By dividing yourself into multiple subtasks, each sub-task can be executed in parallel by different CPUs or by different threads on the same CPU.
It only makes sense to divide the task into several subtasks if it is too large. Splitting a task into subtasks has some overhead, so for small tasks, this split might consume more than the concurrent execution of each subtask.
When to split a task into subtasks is meaningful, and this boundary is also called a threshold. This depends on the decision of each task to a meaningful threshold. Largely depends on the kind of work it is going to do.
When a task splits itself into several subtasks, the task waits for all subtasks to end. Once the subtasks have finished executing, the task can merge all the results into the same result. This is illustrated below:
Lock
The synchronization mechanism implemented with locks is much like synchronized blocks, but more flexible than synchronized blocks. The main differences between locks and synchronized are:
The synchronized block does not guarantee the access order of the threads waiting to enter the block;
Synchronized block can not receive parameters, can not be in the case of a time-out limit to try to access;
Synchronized blocks must be included in a single method, while lock and unlock operations can be in a separate method.
The toolkit provides several types of locks:
Readwritelock: A read-write lock interface that allows multiple threads to read a resource, but only one thread can write at a time. Internal read lock, write lock two interface, respectively, to protect the read operation and write operations. The implementation class is Reentrantreadwritelock.
Reentrantlock: A reentrant lock with the same basic behavior and semantics as the implicit monitor lock accessed using the Synchronized method and the statement, but with a more powerful function. Reentrantlock will be owned by a thread that has recently successfully acquired a lock and has not released the lock. When the lock is not owned by another thread, the thread that called lock succeeds in acquiring the lock and returns. If the current thread already owns the lock, this method will return immediately. There is a counter inside, the thread that owns the lock is locked once, the counter adds 1, each time the counter is released minus 1.
Atomic type
The toolkit provides some types of variables that can be read and written in an atomic manner, and supports one-variable programming without locking thread safety.
Essentially, these classes extend the concept of volatile, using a volatile type of variable to store the actual data.
The toolkit provides 4 types of atomic variable types:
Atomicboolean: An Atom-manipulated Boolean object;
Atomicinteger: An atomic manipulation of the shaping object;
Atomiclong: An atom-manipulated long-shaped object;
Atomicreference: An atomic-manipulated object reference.
Take Atomicinteger as an example. i++ and ++i operations in Java are not thread-safe and require locking. Atomicinteger provides several ways to do this in a thread-safe manner:
| Method |
Defined |
Role |
| Getandincrement |
Public final int Getandincrement |
i++ |
| Getanddecrement |
Public final int Getanddecrement |
i-- |
| Incrementandget |
Public final int Incrementandget |
++i |
| Decrementandget |
Public final int Decrementandget |
-I. |
| Getandadd |
Public final int getandadd (int delta) |
Increase delta return old value |
| Addandget |
Public final int addandget (int delta) |
Add Delta to return new value |
On this basis, the toolkit also provides atomic array types, including Atomicintegerarray, Atomiclongarray, and Atomicreferencearray.
Concurrency Tools
Countdownlatch
Countdownlatch is used for one or more threads to wait for the completion of a specified sequence of operations. When initialized, given a number, the number of countdown methods per call is reduced by one. When other threads call the await method to wait, the thread blocks until the number is reduced to 0 before it starts executing.
Cyclicbarrier Fence
Cyclicbarrier is a synchronization mechanism that synchronizes thread implementations that handle some algorithms. In other words, it is a fence that all threads must wait until all the threads arrive, and then all the threads can continue to do other things. In the process, thread 1 and thread 2 both reach the first fence before they can continue to run. If thread 1 comes first to thread 2, then thread 1 waits for thread 2 to reach the fence, and then two threads to continue running.
Exchanger switch
The Exchanger class represents a rendezvous point where two of threads can exchange objects. Two threads each call the Exchange method for Exchange, and when thread A calls the Exchange method of the interchange object, it becomes blocked until thread B also calls the Exchange method and then swaps the data in a thread-safe manner, after threads A and b continue to run.
Semaphore Signal Volume
Semaphore can easily complete semaphore control, Semaphore can control the number of simultaneous access to a resource, obtain a license through acquire, and if not wait, release releases a license.
Threadlocalrandom Generating concurrent random numbers
Use Math.random to generate random numbers, use atomic variables to save the current seed, so that two threads call the sequence at the same time to get a pseudo-random number, rather than twice times the same number. Threadlocalrandom provides random numbers that are generated concurrently, and is capable of resolving competing battles that occur across multiple threads.
Introduction to the Java 8 concurrency Toolkit