Java 8 No talk about the eight major features

Source: Internet
Author: User
Tags cas thread

Time Stamp Lock

Multithreaded code has long been a poison for server developers (ask Oracle's Java language architect and parallel development guru Brian Goetz). Java's core libraries continue to incorporate complex usage to reduce the thread latency when accessing shared resources. One of these is the classic read-write lock (Readwritelock), which allows you to divide the code into two parts: a write that requires mutual exclusion and a read that does not require mutexes.

It looks good on the surface. The problem is that reading and writing locks can be extremely slow (up to 10 times times), which is already contrary to its original intent. Java 8 introduces a new read-write lock called a timestamp lock. The good news is that this guy is really fast. The bad news is that it's more complex to use and has more state to deal with. And it is not reentrant, which means that a thread is likely to deadlock with itself.

The timestamp lock has an "optimistic" mode in which each lock operation returns a timestamp as a credential, and its corresponding timestamp is required for each unlock operation. If a thread is requesting a write lock that happens to be held by a read operation, the unlock of the read operation will fail (because the timestamp has expired). This time the application needs to start over again, perhaps using a pessimistic mode lock (the timestamp lock is also implemented). You need to handle all of this yourself, and a timestamp can only unlock its corresponding lock--this must be very careful.

Now let's take a look at the example of this lock--

Long stamp = Lock.tryoptimisticread (); Non-blocking path-super fast
work ()///We hope that no write operation occurs at this time
if (lock.validate (stamp)) {
       //success! No write action Interference 
}
else {
       //Certainly another thread has got the write lock, changed the time stamp
       /Lazy said-we switch to the more expensive lock
	
            stamp = Lock.readlock (); This is a traditional read operation lock that will block
       try {
                 //Now no write operation has occurred
                 work ();

       }
       finally {
            lock.unlock (stamp);//use corresponding timestamp to unlock
       }
}

Concurrent addition device

Another outstanding feature of Java 8 is the concurrent "adder", which is particularly meaningful for code that runs on a large scale. One of the most basic concurrency patterns is the reading and writing of a counter. For its part, there are many ways to deal with the problem today, but none is more efficient or elegant than the one provided by Java 8.

So far, the problem has been solved by Atomic class (Atomics), which uses the CPU's "compare and swap" instruction (CAS) to test and set the counter's value directly. The problem is that when a CAS directive fails because of competition, the Atomicinteger class will Deng and try the CAS directive continuously in an infinite loop until it succeeds. In an environment where competitive probabilities are high, this implementation is proving to be very slow.

Look at Java 8 's longadder. This series of classes provides a convenient solution for a large number of parallel read-write code. Use super simple. Simply initialize a Longadder object and use its add () and Intvalue () methods to accumulate and sample the counters.

The difference between this and the old atomic class is that when CAs directives fail because of competition, Adder does not always occupy the CPU, but instead assigns an internal cell object to the current thread to store the increment of the counter. This value is then added to the result of the Intvalue () along with other cell objects to be processed. This reduces the likelihood of repeatedly using CAS directives or blocking other threads.

If you ask yourself, when should you use a concurrent adder instead of an atomic class to manage the counters? The simple answer is--always.

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.