Talking about the underlying implementation of Java concurrency, talking about the underlying implementation of java concurrency
The purpose of concurrent programming is to make the program run faster, but the use of concurrency does not necessarily make the program run faster. Only when the number of concurrent programs reaches a certain level can the advantage of concurrent programming be reflected. So it makes sense to talk about concurrent programming when it comes to high concurrency. Although no program with high concurrency has been developed yet, learning concurrency aims to better understand some distributed architectures. When the concurrency of a program is low, for example, a single-threaded program, the execution efficiency of a single thread is higher than that of multiple threads. Why? Familiar with the operating system, we should know that the CPU implements multithreading by allocating time slices to each thread. In this way, when the CPU switches from one task to another, the status of the previous task is saved. When the task is executed, the CPU continues to run the previous task. This process is called context switching.
In Java multithreading, the volatile keyword synchronized plays an important role. All of them can be used to synchronize threads. But how is it implemented at the underlying layer?
Volatile
Volatile can only ensure the visibility of variables on each thread, but cannot guarantee atomicity. The usage of the Java language volatile is not much mentioned. My suggestion is not to use it unless it works with the class library in package java. util. concurrent. atomic. For more explanations, see this article.
Introduction
See the following code
package org.go;public class Go { volatile int i = 0; private void inc() { i++; } public static void main(String[] args) { Go go = new Go(); for (int i = 0; i < 10; i++) { new Thread(() -> { for (int j = 0; j < 1000; j++) go.inc(); }).start(); } while(Thread.activeCount()>1){ Thread.yield(); } System.out.println(go.i); }}
The result of each execution of the above Code is different, and the output number is always less than 10000. This is because I ++ is not an atomic operation during inc. Some may suggest using synchronized to synchronize inc (), or using a lock in package java. util. concurrent. locks to control thread synchronization. But they are not as good as the following solutions:
package org.go;import java.util.concurrent.atomic.AtomicInteger;public class Go { AtomicInteger i = new AtomicInteger(0); private void inc() { i.getAndIncrement(); } public static void main(String[] args) { Go go = new Go(); for (int i = 0; i < 10; i++) { new Thread(() -> { for (int j = 0; j < 1000; j++) go.inc(); }).start(); } while(Thread.activeCount()>1){ Thread.yield(); } System.out.println(go.i); }}
At this time, if you do not understand the implementation of atomic, you will not doubt that the bottom layer of AtomicInteger is implemented using locks, so it may not be efficient. So let's take a look at what it is.
Internal Implementation of atomic classes
Whether it's AtomicInteger or concurrent1_queue's Node class concurrent1_queue. Node, they all have a static variable
Private static final sun. misc. Unsafe UNSAFE;, which is a Java encapsulation of the C ++ object sun: misc: Unsafe that implements atomic semantics. I want to see the underlying implementation. I have the source code of gcc4.8 at hand. Compare it with the local path to find the Github path.
Use the getAndIncrement () interface as an example.
AtomicInteger. java
private static final Unsafe unsafe = Unsafe.getUnsafe();public final int getAndIncrement() { for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return current; } }public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); }
Note that this for loop will be returned only when compareAndSet is successful. Otherwise, compareAndSet will continue.
The compareAndSet implementation is called. Here, I noticed that the implementation of the Oracle JDK is slightly different. If you view the src under the JDK, you can see that the Oracle JDK is the getAndIncrement () called Unsafe (), however, I believe that Oracle JDK implements Unsafe. in java, only compareAndSet should be called, because a compareAndSet can implement atomic operations to increase, decrease, and set values.
Unsafe. java
public native boolean compareAndSwapInt(Object obj, long offset, int expect, int update);
Through the implementation of C ++ called by JNI.
NatUnsafe. cc
jbooleansun::misc::Unsafe::compareAndSwapInt (jobject obj, jlong offset, jint expect, jint update){ jint *addr = (jint *)((char *)obj + offset); return compareAndSwap (addr, expect, update);}static inline boolcompareAndSwap (volatile jint *addr, jint old, jint new_val){ jboolean result = false; spinlock lock; if ((result = (*addr == old))) *addr = new_val; return result;}
Unsafe: compareAndSwapInt calls the static function compareAndSwap. CompareAndSwap uses the spinlock as the lock. Here, the spinlock has the meaning of LockGuard. It is locked during construction and released during structure analysis.
We need to focus on the spinlock. This ensures that before the release of the spinlock, It is the true implementation of atomic operations.
What is spinlock?
A spin lock is a sort of loop wait (busy waiting) to obtain the Lock of a resource. Unlike mutex's process of blocking the current thread and releasing CPU resources to wait for required resources, spinlock does not enter the process of suspending, waiting for conditions to meet, and re-competing for CPU. This means that the spin lock is better than mutex only when the lock wait cost is lower than the thread's context switch cost.
NatUnsafe. cc
class spinlock{ static volatile obj_addr_t lock;public:spinlock () { while (! compare_and_swap (&lock, 0, 1)) _Jv_ThreadYield (); } ~spinlock () { release_set (&lock, 0); }};
Take a static variable static volatile obj_addr_t lock; as the flag, a Guard is implemented through C ++ RAII. So the so-called lock is actually a static member variable obj_addr_t lock, in C ++, volatile cannot be synchronized. The constructor calls compare_and_swap and a static variable lock. when the lock variable is 1, you need to wait; when it is 0, it is set to 1 through atomic operations, indicating that you have obtained the lock.
It is really an accident to use a static variable here, which is equivalent to all lockless structures sharing the same variable (actually size_t) to identify whether to lock. When this variable is set to 1, all other variables that use the spinlock must wait. Why not add a private variable volatile obj_addr_t lock as sun: misc: Unsafe and pass it as a construction parameter to the spinlock? This is equivalent to sharing a flag space for each UnSafe instance. Will the effect be better?
_ Jv_ThreadYield in the following file, the system calls sched_yield (man 2 sched_yield) to give up CPU resources. Macro HAVE_SCHED_YIELD is defined in configure, which means that if the definition is canceled during compilation, spinlock is called a true spin lock.
Posix-threads.h
inline void_Jv_ThreadYield (void){#ifdef HAVE_SCHED_YIELD sched_yield ();#endif /* HAVE_SCHED_YIELD */}
This lock. h has different implementations on different platforms. We use the ia64 (Intel AMD x64) platform as an example. Other implementations can be seen here.
Ia64/locks. h
typedef size_t obj_addr_t;inline static boolcompare_and_swap(volatile obj_addr_t *addr, obj_addr_t old, obj_addr_t new_val){ return __sync_bool_compare_and_swap (addr, old, new_val);}inline static voidrelease_set(volatile obj_addr_t *addr, obj_addr_t new_val){ __asm__ __volatile__("" : : : "memory"); *(addr) = new_val;}
_ Sync_bool_compare_and_swap is a built-in function of gcc. The compilation command "memory" is used to implement the memory barrier.
- Generally, if the CPU Hardware supports the command cmpxchg (which guarantees atomicity from the hardware and is very efficient without a doubt), _ sync_bool_compare_and_swap should be implemented using cmpxchg.
- CPU architecture that does not support cmpxchg can be implemented by locking the CPU bus by using the lock command prefix.
- If the lock command is not supported, it may be implemented through APIC.
In short, the hardware ensures multi-core CPU synchronization, And the Unsafe implementation is as efficient as possible. GCC-java is fairly efficient. I believe that Oracle and OpenJDK will not be worse.
Atomic operations and built-in GCC atomic operations
Atomic operation
Java expressions and C ++ expressions are not atomic operations, that is, you are in the Code:
// Assume that I is the shared variable I ++ between threads;
In a multi-threaded environment, access to I is non-atomic and is actually divided into the following three operands:
- From cache to register
- Add 1 to the Register
- Save to cache
The compiler will change the execution sequence, so the execution results may not be expected.
Built-in atomic operations of GCC
Gcc has the following built-in atomic operations, which are added from 4.1.2. Previously, they were implemented using inline assembly.
type __sync_fetch_and_add (type *ptr, type value, ...)type __sync_fetch_and_sub (type *ptr, type value, ...)type __sync_fetch_and_or (type *ptr, type value, ...)type __sync_fetch_and_and (type *ptr, type value, ...)type __sync_fetch_and_xor (type *ptr, type value, ...)type __sync_fetch_and_nand (type *ptr, type value, ...)type __sync_add_and_fetch (type *ptr, type value, ...)type __sync_sub_and_fetch (type *ptr, type value, ...)type __sync_or_and_fetch (type *ptr, type value, ...)type __sync_and_and_fetch (type *ptr, type value, ...)type __sync_xor_and_fetch (type *ptr, type value, ...)type __sync_nand_and_fetch (type *ptr, type value, ...)bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...)type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)__sync_synchronize (...)type __sync_lock_test_and_set (type *ptr, type value, ...)void __sync_lock_release (type *ptr, ...)
Note that:
- The relationships between _ sync_fetch_and_add and _ sync_add_and_fetch correspond to I ++ and ++ I. Miscellaneous
- Two CAS implementations: If the bool version compares oldval with ptr successfully, and sets the value newval for ptr to return true; the other returns the value of * ptr
- _ Sync_synchronize adds a full memory barrier
OpenJDK files
The following lists the atomic operation implementation of OpenJDK9 on Github, hoping to help people who need to know it. After all, OpenJDK is more widely used than Gcc. ---- But after all, there is no source code for the Oracle JDK, although it is said that the source code gap between OpenJDK and Oracle is very small.
AtomicInteger. java
Unsafe. java: compareAndExchangeObject
Unsafe. cpp: Unsafe_CompareAndExchangeObject
Oop. inline. hpp: oopDesc: atomic_compare_exchange_oop
Atomic_linux_x86.hpp: Atomic: cmpxchg
inline jlong Atomic::cmpxchg (jlong exchange_value, volatile jlong* dest, jlong compare_value, cmpxchg_memory_order order) { bool mp = os::is_MP(); __asm__ __volatile__ (LOCK_IF_MP(%4) "cmpxchgq %1,(%3)" : "=a" (exchange_value) : "r" (exchange_value), "a" (compare_value), "r" (dest), "r" (mp) : "cc", "memory"); return exchange_value;}
Here, a prompt should be given to Java programmers who are not familiar with C/C ++. The format of Embedded Assembly commands is as follows:
_ Asm _ [_ volatile _] (assembly template // assembly template: [output operand list] // input list: [input operand list] // output list: [clobber list]) // destroys the list.
% 1, % 3, and % 4 in the Assembly template correspond to the following parameter lists {"r" (exchange_value), "r" (dest), "r" (mp )}, the parameter lists are separated by commas (,) and sorted from 0. The output parameter is placed on the right of the first colon, and the output parameter is placed on the right of the second colon. "R" indicates to put it into the General Register, "a" indicates the register EAX, and "=" indicates to use it for output (write back ). The cmpxchg command implicitly uses the EAX register as the parameter % 2.
Other details are not listed here. The Gcc implementation is to pass the pointer to be exchanged, and assign values directly after the comparison is successful (assign values not atomic). Atomicity is guaranteed through the spinlock.
The implementation of OpenJDK is to pass the pointer to be exchanged and assign values directly through the Assembly command cmpxchgq, Which is atomically guaranteed by the Assembly command. Of course, the bottom layer of the gcc spinlock is also guaranteed by cmpxchgq.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.