Java thread-CAS spin lock (Spin-lock)

Source: Internet
Author: User
Tags object object

I. The background of the spin lock proposed

Because some resources in a multiprocessor system environment are limited and sometimes require mutually exclusive access (mutual exclusion), a lock mechanism is introduced, and only the process that acquires the lock can obtain access to the resource. that is, only one process can acquire a lock at a time to enter the the critical section of the same time can not be two or more than two processes into the critical area, when exiting the critical section of the release lock. There is always a situation when designing mutex algorithms, that is, what happens when a process without a lock is acquired? There are usually 2 ways of handling it. One is that the caller who has not acquired the lock has been circulating there to see if the self-rotating lock has released the lock, which is the spin lock, he does not have to block the county (non-blocking), and the other is that the process without acquiring a lock blocks (BLOCKING) itself, Requests that the OS dispatch another thread on the processor, which is the mutex.

Second, the principle of spin lock

Like a mutex, an execution unit that accesses a shared resource protected by a spin lock must first obtain a lock, which must be released after the shared resource has been accessed. If no execution unit holds the lock when acquiring a spin lock, the lock is immediately obtained, and if the lock has a hold when the spin lock is acquired, then the acquire lock operation will spin there until the lock is released by the hold of the spin lock. From this we can see that the spin lock is a low-level protection of data structures or snippets of the original way, such a lock may have two problems:

    • Recursive deadlock : Attempting to get a spin lock recursively will inevitably cause a deadlock: the holding instance of the recursive program loops in the second instance to attempt to obtain the same spin lock, which does not release this spin lock. Using a spin lock in a recursive program should adhere to the following strategies: The recursive program must never invoke itself when holding a spin lock, or attempt to obtain the same spin lock when recursive calls are made. In addition, if a process has already locked the resource, even the other processes that are applying for the resource will not be able to get resources to go into the dead loop until the process of requesting the resources is spinning wildly.
    • consumes too much CPU resources . If there is no limit, because the applicant has been circulating waiting, so the spin lock when locked, if not successful, not sleep, will continue to try, a single CPU when the spin lock will make other process can not move. Therefore, the general spin lock implementation will have a parameter that limits the maximum number of persistent attempts. After the spin lock is exceeded, the current time slice is discarded. Wait for the next chance.

This shows that the spin lock comparison is suitable for lock users to keep the lock time relatively short . It is because the spin lock user generally keeps the lock time very short, so it is very necessary to choose spin instead of sleep, and the efficiency of the spin lock is much higher than the mutual exclusion lock.

Third, Java CAS

CAS is a system primitive (the so-called primitive language belongs to the operating system language category. A process in which a primitive is composed of several directives used to accomplish a certain function. Primitive or atomic action is a program of several machine instructions that accomplishes a particular function, which is indivisible-that is, the execution of the primitive must be sequential and not allowed to be interrupted during execution. CAS is the abbreviation for compare and set. CAS has 3 operands, a memory value of V, an old expected value of a, and a new value to be modified B. If and only if the expected value A and the memory value of the V phase, the memory value of V is modified to B, otherwise do nothing.

On the x86 platform, the CPU provides a means of locking the bus during instruction execution. The CPU chip has a lead #hlock pin, if the assembly language program in a command prefix "LOCK", after the assembly of the machine code so that the CPU in the execution of this instruction at the time of the #hlock pin to pull down, continue to the end of this instruction to release, So that the bus lock, so that the other CPU on the same bus temporarily can not access the memory through the bus, to ensure that this instruction in the multi-processor environment of the atomicity

Sun.misc.Unsafe is an internal class inside the JDK, which is strictly protected by the JDK because he provides a lot of low-level memory operations and system functionality. If this class is used incorrectly, there will be no "exceptions" thrown out, or even a JVM outage. This is why the name of this class is unsafe. So when you use this class, you must understand what you are doing. 3 CAS operations are available in this class

Method name Explain
Compareandswapint (Object object, long address, int expected, int newvalue) Compares the property of an int of an object (accessed as an address), if his data value is expected, is set to NewValue, returns True, otherwise returns false
Compareandswaplong (Object object, long address, long expected, long NewValue) Compares the property of a long type of object, accessed as an address, and, if his data value is expected, is set to NewValue, which returns true; otherwise false
Compareandswaplong (Object object, long address, object expected, object NewValue) Compares the property of an object type of objects (accessed as an address), if his data value is expected, is set to NewValue, returns True, otherwise returns false

Iv. Java spin lock application-Atom pack

After Jdk1.5, the Java.util.concurrent.atomic package is provided, which provides a set of atomic classes. The basic feature is that in a multithreaded environment, when there are multiple threads executing the methods contained in the instances of these classes, there is exclusivity, that is, when a thread enters the method, executes the instruction in it, it is not interrupted by another thread, and the other thread is like a spin lock until the method execution is completed, The JVM chooses a second thread from the waiting queue to enter, which is only a logical understanding. It is actually implemented with hardware-related instructions that do not block threads (or simply block at the hardware level ). The classes can be divided into 4 groups

    • Atomicboolean,atomicinteger,atomiclong,atomicreference
    • Atomicintegerarray,atomiclongarray
    • Atomiclongfieldupdater,atomicintegerfieldupdater,atomicreferencefieldupdater
    • Atomicmarkablereference,atomicstampedreference,atomicreferencearray

Let's see the code for a spin lock in a atomicboolean.

 Public Final boolean Getandset (boolean  newvalue) {   for  (;;) {       boolean current = get ();        if (Compareandset (current, newvalue))            return Current ;   }}

Reference

Http://baike.baidu.com/view/1250961.htm?fr=aladdin

Java thread-CAS spin lock (Spin-lock)

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.