Java.util.concurrent.atomic Principle Detailed

Source: Internet
Author: User

15 years ago, multiprocessor systems were highly specialized and cost $ hundreds of thousands of (most of them had two to four processors). Multiprocessor systems are now cheap and large in number, with multi-processing support built into almost every major microprocessor, many of which support dozens of or hundreds of processors.

To use the capabilities of a multiprocessor system, it is often necessary to construct the application using multithreading. But just as anyone who writes concurrent applications can tell you, it's not enough to get good hardware utilization, simply splitting the work across multiple threads, and you have to make sure that the threads do work most of the time, not waiting for more work, or waiting to lock the shared data structure.

Problem: coordination between threads

If there is no need for coordination between threads, then almost no task can actually be parallel. Take the thread pool as an example, where the tasks performed are usually independent of each other. If the thread pool takes advantage of a public work queue, the process of removing elements from the work queue or adding elements to a task column must be thread-safe, and this means reconciling access to a link pointer between the head, tail, or node. It is this coordination that has led to all problems.

Standard Method: Lock

In the Java language, the traditional way to coordinate access to shared fields is to use synchronization to ensure that all access to the shared field is completed with the appropriate locks. By synchronizing, you can determine (assuming that the class is written correctly) that all threads with a lock that protects a given set of variables will have exclusive access to those variables, and that the changes made to those variables will be visible when other threads later acquire the lock. The downside is that if the lock is too competitive (the thread often asks for the lock when another thread has a lock), the throughput is compromised because the synchronization of the competition is very expensive. (Public Service Announcement: for modern JVMs, non-competitive synchronization is now very inexpensive.)

Another problem with locking-based algorithms is that if you delay a thread that has a lock (because of a page fault, scheduling delay, or other unexpected delay), there is no thread that requires the lock to continue running.

You can also use mutable variables to store shared variables at a lower cost than synchronization, but they have limitations. While it is guaranteed that other variables can immediately see writes to mutable variables, the read-modify-write order of the atomic operation cannot be rendered, which means (for example) that mutable variables cannot be used to reliably implement mutual exclusion (mutex locking) or counters.

Implementing counters and mutexes with locks

If you develop a thread-safe counter class, this exposes get() , increment() and decrement() operates. Listing 1 shows an example of how this class can be implemented using locking (synchronization). Note that all methods, even those that require synchronization get() , make the Class A thread-safe class, ensuring that no update information is lost, and that all threads see the latest value of the counter.

Listing 1. Synchronized counter Classes
public class Synchronizedcounter {    private int value;    public synchronized int GetValue () {return value;}    public synchronized int increment () {return ++value;}    public synchronized int Decrement () {return--value;}}

increment()and decrement() operations are atomic read-modify-write operations, in order to implement the counter safely, you must use the current value and add a value to it, or write out a new value, all of which are considered an operation, and other threads cannot interrupt it. Otherwise, if two threads attempt to perform an increase at the same time, the unfortunate crossover of the operation will cause the counter to be implemented only once, instead of being implemented two times. (Note that this operation cannot be done reliably by making the value instance variable variable.) )

The read-modify-write combinations of atoms are shown in many concurrency algorithms. The code in Listing 2 implements a simple mutex, and the acquire() method is also an atomic read-modify-write operation. To obtain mutexes, you must make sure that no one else has the mutex ( curOwner = Thread.currentThread() ), and then record the fact that you own the mutex ( curOwner = Thread.currentThread() ), all of which makes it impossible for other threads to appear in the middle and modify curOwner field .

Listing 2. Mutually exclusive classes for synchronization
public class Synchronizedmutex {    private Thread curowner = null;    public synchronized void Acquire () throws Interruptedexception {        if (thread.interrupted ()) throw new Interruptedexception ();        while (Curowner! = null)             wait ();        Curowner = Thread.CurrentThread ();    }    Public synchronized void release () {        if (Curowner = = Thread.CurrentThread ()) {            curowner = null;            Notify ();        } else            throw new IllegalStateException ("Not owner of Mutex");}    }

The counter classes in Listing 1 can work reliably and perform well when there is little or no competition. However, when the competition is intense, this can greatly impair performance, because the JVM takes more time to schedule threads, manage competition, and wait for thread queues, while the actual work (such as increasing counters) is less time-intensive. You can think back to the diagram in the last column, which shows how throughput will drop dramatically once multiple threads use synchronization to compete for a built-in monitor. While this column shows ReentrantLock how new classes can be more scalable to replace synchronization, there are better workarounds for some issues.

Locking issues

With locking, if a thread tries to acquire a lock that other threads already have, then the thread will be blocked until the lock is available. This approach has some obvious drawbacks, including that it cannot do anything else when a thread is blocked to wait for a lock. If the blocked thread is a high-priority task, then the scenario can result in very bad results (known as the risk of priority inversion ).

There are other dangers to using locks, such as deadlocks (deadlocks occur when multiple locks are obtained in an inconsistent order). Even without this danger, locking is only a relatively coarse-grained coordination mechanism, which is also ideal for managing simple operations such as adding counters or updating mutex owners. It would be better if there was a finer-grained mechanism to reliably manage concurrent updates to individual variables, and in most modern processors.


Hardware Synchronization Primitives

As mentioned earlier, most modern processors include support for multi-processing. Of course, this support includes multiple processors that can share external devices and main memory, and it usually includes the addition of instruction systems to support the special requirements of multi-processing. In particular, almost every modern processor has instructions to update shared variables in a way that detects or blocks the concurrent access of other processors.

Compare and Exchange (CAS)

The first processor that supports concurrency provides test and set operations for atoms, typically running this operation on the organization. The most common way to use today's processors, including Intel and Sparc processors, is to implement primitives named Compare and convert or CAS. (in Intel processors, the CMPXCHG series implementations are compared and exchanged via directives.) The PowerPC processor has a pair of instructions called "Load and hold" and "conditional storage" that implement the same target, and MIPS is similar to the PowerPC processor except that the first instruction is called "Load link". )

The CAS operation consists of three operands-the memory location (V), the expected original value (A), and the new value (B). If the value of the memory location matches the expected original value, the processor automatically updates the location value to the new value. Otherwise, the processor does nothing. In either case, it will return the value of that location before the CAS directive. (In some special cases of CAs, only the CAS will be returned successfully, not the current value.) CAS effectively illustrates that "I think position V should contain a value of A; If you include this value, B will be placed in this position; otherwise, do not change the position, just tell me the value of this position now." ”

CAS is typically used for synchronization by reading value A from address V, performing a multi-step calculation to obtain the new value B, and then using CAs to change the value of V from A to B. If the value at V has not changed at the same time, the CAS operation succeeds.

CAS-like directives allow the algorithm to perform a read-modify-write operation without fear of other threads modifying the variable at the same time, because if another thread modifies the variable, the CAS detects it (and fails) and the algorithm can recalculate the operation. Listing 3 illustrates the behavior of CAS operations (not performance characteristics), but the value of CAS is that it can be implemented in hardware and is extremely lightweight (in most processors):

Listing 3. Code that describes the behavior (rather than the performance) of comparing and exchanging
public class Simulatedcas {     private int value;     public synchronized int GetValue () {return value;} public synchronized int Compareandswap (int expectedvalue, int newvalue) {         int oldValue = value;         if (value = = expectedvalue)             value = newvalue;         return oldValue;}     }
Implementing counters using CAS

A CAS-based concurrency algorithm is called a no-lock algorithm because threads no longer have to wait for locks (sometimes called mutexes or critical parts, depending on the terminology of the threading platform). Regardless of whether the CAS operation succeeds or fails, in either case, it is completed in a predictable period of time. If the CAS fails, the caller can retry the CAS operation or take other appropriate actions. Listing 4 shows the rewritten counter class to use CAS instead of locking:

Listing 4. Implementing counters using Compare and Exchange
public class Cascounter {    private simulatedcas value;    public int GetValue () {        return value.getvalue ();    }    public int increment () {        int oldValue = Value.getvalue ();        while (Value.compareandswap (OldValue, OldValue + 1)! = oldValue)            oldValue = Value.getvalue ();        return oldValue + 1;    }}


No lock and no wait algorithm

If each thread continues to operate on any delay (or even failure) of another thread, it can be said that the algorithm is not waiting . In contrast, the lock-free algorithm requires only one thread to always perform operations. (Another definition of no wait is to ensure that each thread calculates its own operations correctly in its limited steps, regardless of the operation, timing, crossover, or speed of other threads.) This limit can be a function of the number of threads in the system, for example, if you have 10 thread, each thread performs one CasCounter.increment() operation, and in the worst case, each thread will have to retry up to nine times to complete the increase. )

Over the past 15 years, there has been a lot of research on the no-wait and no-lock algorithm (also known as a nonblocking algorithm ), and many general data structures have found nonblocking algorithms. Non-blocking algorithms are widely used in operating system and JVM levels for tasks such as threading and process scheduling. While their implementations are complex, they have many advantages over locking-based alternative algorithms: they avoid the risk of priority inversion and deadlock, which is less competitive, the coordination takes place at finer granularity, allows for higher levels of parallelism, and so on.

Atomic Variable Class

Prior to JDK 5.0, without the use of native code, no wait-and-lock algorithms could be written in the Java language. java.util.concurrent.atomicthis has changed since the atomic variable class was added to the package. All atomic variable classes expose comparisons and set primitives (similar to comparison and exchange), which are implemented using the fastest native architecture available on the platform (comparing and exchanging, loading link/conditional storage, and, in the worst case, rotating locks). The java.util.concurrent.atomic package provides 9 styles of atomic variables (;; AtomicInteger ; AtomicLong AtomicReference AtomicBoolean ; atomic integer type; long type; reference; An array form of an atomic tag reference and a stamp reference class that atomically updates a pair of values).

The atomic variable class can be thought of as a volatile generalization of variables that extend the concept of mutable variables to support the comparison of atomic conditions and to set up updates. Read and write atomic variables have the same access semantics as read and write access to mutable variables.

Although the atomic variable class surface looks like the example in Listing 1 SynchronizedCounter , the similarity is only superficial. Below the surface, the operation of the atomic variable becomes the hardware primitives provided by the platform for concurrent access, such as comparison and exchange.

Finer granularity means more lightweight

The general technique for adjusting the scalability of competing concurrent applications is to reduce the granularity of the locked objects used, hoping that more lock requests will become non-competitive from the competition. The same result can be achieved by converting from locks to atomic variables, and by switching to a finer-grained coordination mechanism, there is less competition, which improves throughput.

ABA issues

Because CAs primarily asks if "V's value is still a" before changing V, it will confuse the CAS-based algorithm if you change the value from a to B and then back to a when you first read V and perform a CAS operation on V. In this case, the CAS operation succeeds, but in some cases the results may not be what you expect. (Note that the counters and mutex examples in listings 1 and 2 do not have this problem, but not all algorithms do.) This type of problem is called an ABA problem , and is typically handled by associating a tag or version number with each value to be performed by a CAS operation, and atomically updating values and tags. AtomicStampedReferenceclass supports this method.


Atomic variables in the Java.util.concurrent

Whether direct or indirect, almost java.util.concurrent all classes in a package use atomic variables instead of synchronization. Similar ConcurrentLinkedQueue classes use atomic variables to implement a no-wait algorithm directly, whereas similar ConcurrentHashMap classes use ReentrantLock locks when needed. Then, ReentrantLock use atomic variables to maintain the queue of threads waiting to be locked.

Without JVM improvements in JDK 5.0, these classes could not be constructed, and these improvements exposed (to class libraries, not user classes) interfaces to access hardware-level synchronization primitives. Then, the atomic variable classes and other classes in java.util.concurrent expose these capabilities to the user class.


Use atomic variables for higher throughput

Last month, I described ReentrantLock how to provide scalability benefits relative to synchronization, as well as a simple, highly competitive example benchmark that simulates rotating dice with pseudo-random number generators. I showed you the implementation that was coordinated through synchronization, ReentrantLock and fairness ReentrantLock , and showed the results. This month, I'll add another implementation to the benchmark, using AtomicLong an implementation that updates the PRNG state.

Listing 5 shows the PRNG implementation using synchronization and the use of the CAS alternative implementation. Note that you want to execute CAs in a loop because it may fail one or more times to succeed, and the code that uses CAs always does.

Listing 5. Thread-safe PRNG using synchronous and atomic variables
public class Pseudorandomusingsynch implements pseudorandom {private int seed;    Public pseudorandomusingsynch (int s) {seed = s;}        public synchronized int Nextint (int n) {int s = seed;        Seed = Util.calculatenext (seed);    return s% n;    }}public class Pseudorandomusingatomic implements pseudorandom {private final atomicinteger seed;    Public pseudorandomusingatomic (int s) {seed = new Atomicinteger (s); } public int Nextint (int n) {for (;;)            {int s = seed.get ();            int nexts = Util.calculatenext (s);        if (Seed.compareandset (S, nexts)) return s% n; }    }}

The figures in Figure 1 and figure 2 below resemble those in the previous month, but add a single line to the atomic-based approach. These graphs show the randomly occurring throughput (in RPM per second) on 8-way Ultrasparc3 and on a single processor Pentium 4 using a different number of threads. The number of threads in the test is not real, and these threads exhibit much more competition than usual, so they show a balance with the atomic variable in the number of threads that are much lower than the actual program ReentrantLock . You will see that although ReentrantLock there are more advantages than synchronization, the ReentrantLock atomic variables provide additional improvements relative to them. (because there is very little work done in each unit of work, it may not be possible to fully explain what the scalability benefits of atomic variables are compared to reentrantlock.) )

Figure 1. 8-way Ultrasparc3 in sync, Reentrantlock, fair Lock, and Atomiclong benchmark throughput Figure 2. Baseline throughput for synchronization, Reentrantlock, Fair Lock, and Atomiclong in single-processor Pentium 4

Most users are less likely to use atomic variables themselves to develop nonblocking algorithms-they are more likely java.util.concurrent to use the versions provided in, such as ConcurrentLinkedQueue . But in case you want to know how the performance of these classes is improved compared to similar features in the previous JDK, you can use the fine-grained, hardware-level concurrency primitives exposed through the atomic variable classes.

Developers can use atomic variables directly as high-performance replacements for shared counters, ordinal generators, and other independent shared variables, otherwise they must be protected by synchronization.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java.util.concurrent.atomic Principle Detailed

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.