Java High concurrency Ten: JDK8 new support for concurrency detailed _java

Source: Internet
Author: User
Tags cas

1. Longadder

and Atomiclong similar use, but the performance is better than Atomiclong.

Both Longadder and Atomiclong use atomic operations to improve performance. But longadder on the basis of Atomiclong, hot spot separation is similar to the reduction of lock granularity in the lock operation, and a lock is separated into several locks to improve performance. In the absence of locks, a similar approach can be used to increase the success rate of CAS, thereby improving performance.

Longadder schematic diagram:

The implementation of the Atomiclong is the internal value variable, when multithreading and from the increase, since the reduction, all through the CAS directives from the machine instruction level operation to ensure concurrent atomicity. The only reason to restrict atomiclong efficiency is high concurrency, high concurrency means higher failure probability of CAs, more retries, more lines Chenghong, higher CAS failure probability, a vicious circle, and atomiclong efficiency.

And Longadder will split a value into several cell, add all the cell together, is value. So the longadder operation, only need to operate on different cell, different threads for different cell CAs operation, CAS success rate of course high (imagine 3+2+1=6, one thread 3+1, another thread 2+1, and finally 8, Longadder does not have a multiplication Division API).

However, in the case of concurrent number is not very high, split into several cell, also need to maintain the cell and sum, less efficient than the implementation of Atomiclong. Longadder a clever way to solve the problem.

Initially, the Longadder and Atomiclong are the same, and only when CAs fails will the value be split into the cell, and each failure, it will increase the number of the cell, so that, at low concurrency, the same efficiency, in high concurrency, this "adaptive" approach, When a certain number of cell is reached, CAS will not fail, and the efficiency is greatly increased.

Longadder is a strategy to change time in space.

2. Completablefuture

Implement Completionstage interfaces (more than 40 methods), most of which are used in functional programming. and supports streaming calls

Completablefuture is an enhanced version of future in Java 8

Simple implementation:

Import Java.util.concurrent.CompletableFuture;

public class Askthread implements Runnable {
 completablefuture<integer> re = null;

 Public Askthread (Completablefuture<integer> re) {
 this.re = re;
 }

 @Override public
 Void Run () {
 int myre = 0;
 try {
 Myre = re.get () * Re.get ();
 } catch (Exception e) {
 }
 System.out.println (Myre);
 }

 public static void Main (string[] args) throws Interruptedexception {
 final completablefuture<integer> future = new completablefuture<integer> ();
 New Thread (New Askthread (future)). Start ();
 Simulation of long time calculation process
 thread.sleep (1000);
 Inform the completion result
 future.complete;
 }


Future the most disturbing is to wait, to own to check whether the task is completed, in future, the task to complete the time is not controllable. The biggest improvement in Completablefuture is that the time to complete the task is also open.

Future.complete (60);

Used to set the finish time.

Asynchronous execution of Completablefuture:

public static integer calc (integer para) {
 try {
 //Simulate a long time execution
 thread.sleep (1000);
 } catch ( Interruptedexception e) {
 } return
 para * para;
 }

 public static void Main (string[] args) throws Interruptedexception,
 executionexception {
 final completablefuture<integer> future = Completablefuture
 . Supplyasync (()-> calc);
 System.out.println (Future.get ());
 }
Completablefuture Streaming calls: public

static integer calc (integer para) {
 try {
 //Simulate a long time execution
 Thread.Sleep (1000);
 } catch (Interruptedexception e) {
 } return
 para * para;
 }

 public static void Main (string[] args) throws Interruptedexception,
 executionexception {
 completablefuture <Void> fu = completablefuture
 supplyasync (()-> Calc)
 . Thenapply ((i)-> integer.tostring (i )
 . Thenapply ((str)-> "\" "+ str +" \ ")
 . Thenaccept (system.out::p rintln);
 Fu.get ();
 }

Combine multiple completablefuture:

public static integer calc (integer para) {return
 para/2;
 }

 public static void Main (string[] args) throws Interruptedexception,
 executionexception {
 completablefuture <Void> fu = completablefuture
 supplyasync (()-> Calc)
 . Thencompose (
  (i)-> Completablefuture.supplyasync (()-> calc (i))
 . Thenapply ((str)-> "\" + str + "\")
 . Thenaccept ( System.out::p rintln);
 Fu.get ();
 }

These examples are more emphasis on the Java8 of some of the new features, here is a simple example to illustrate the characteristics, do not delve into.
Completablefuture has little to do with performance, and more to support functional programming and enhancements in functionality. Of course it's open. The setting of the finish time is a big bright spot.

3. Stampedlock

In the previous article just mentioned the lock separation, and the important realization of the lock separation is readwritelock. And Stampedlock is an improvement of readwritelock. The difference between Stampedlock and Readwritelock is that stampedlock think that reading should not block writing, stampedlock that when reading and writing are mutually exclusive, reading should be reread rather than not writing thread. This design solves the problem of reading and writing, and using Readwritelock can create a thread-hungry phenomenon.

So Stampedlock is an improvement in favor of writing threads.

Stampedlock Example:

Import Java.util.concurrent.locks.StampedLock;

public class Point {
 private double x, y;
 Private final Stampedlock sl = new Stampedlock ();

 void Move (double deltax, double deltay) {//A exclusively locked method
 Long stamp = Sl.writelock ();
 try {
 x + = DeltaX;
 Y + + DeltaY;
 } finally {
 sl.unlockwrite (stamp);
 }
 }

 Double Distancefromorigin () {//A Read-only method
 Long stamp = Sl.tryoptimisticread ();
 Double CurrentX = x, currenty = y;
 if (!sl.validate (stamp)) {
 stamp = Sl.readlock ();
 try {
 currentx = x;
 CurrentY = y;
 } finally {
 sl.unlockread (stamp);
 }
 }
 Return math.sqrt (CurrentX * currentx + currenty * currenty);
 }


The above code simulates the write thread and read thread, Stampedlock according to stamp to see whether mutually exclusive, write one time stamp change add a value

Tryoptimisticread ()

is just said to read and write is not mutually exclusive situation.

Each time a read thread is read, it is judged first

if (!sl.validate (stamp))

Validate will first see if a write thread is writing and then judge whether the input value is the same as the current stamp, that is, whether the read thread will read the latest data.

If a write thread is being written, or if the stamp value is different, the return fails.

If the judgment fails, of course you can repeatedly try to read, in the sample code, and did not let it repeat the attempt to read, and the use of the optimistic lock to degenerate into a normal read lock to read, this is a pessimistic reading method.

Stamp = Sl.readlock ();

The realization thought of Stampedlock:

CLH spin Lock: When a lock request fails, the read thread is not suspended immediately, and a waiting thread queue is maintained in the lock, all request locks, but no successful threads are recorded in this queue. Each node (a node represents a thread) holds a tag bit (locked) to determine whether the current thread has released the lock. When a thread attempts to acquire a lock, the trailing node of the current waiting queue is taken as its predecessor node. and use code like the following to determine if the pre-ordered node has successfully released the lock

while (pred.locked) {
}

This loop is constantly waiting for the previous node to release the lock, so that the spin makes the current thread will not be suspended by the operating system, thereby improving performance.
Of course, there is no endless spin, which suspends threads after several spins.

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.