Multi-threaded synchronization

Source: Internet
Author: User
Tags cas finally block object object

In Java, there are four ways to synchronize mutually exclusive access: The synchronized, Lock, wait ()/notify ()/Notifyall () method, and the CAS (Hardware CPU synchronization primitive).

First, synchronized

1. Synchronizing code blocks

1 synchronized (object) {2 }

Indicates that the thread will lock object object when executing. (Note that this object can be an object of any class, or you can use the This keyword to represent this object or a class object).
Perhaps only a few lines of code in a method will involve thread synchronization problems, so the synchronized block is more granular than the Synchronized method to control access to multiple threads, and only the contents of the synchronized block cannot be accessed by multiple threads at the same time. The other statements in the method can still be accessed by multiple threads at the same time (both before and after the synchronized block).

2. For non-static methods

1  Public synchronized void Increase () {2      i++; 3 }

When a thread accesses an object's synchronized method, locks the object, and no other thread can access the object's synchronized method until the previous thread executes the method (or throws an exception), releasing the object's lock. Other threads will be able to access the object's synchronized method again.

3. Acting on static methods

1 Static int i=0; 2  Public synchronized void Increase () {3      i++; 4 }    

When a synchronized keyword modification method is also modified by static, the non-static synchronization method locks the object, but the static method is not the object, but belongs to the class, which locks the class object of the classes in which the method resides.

Second, the use of Lock.

Java.util.concurrent.locks common classes and interfaces in a package:

Lock interface and its implementation class Reentrantlock

Readwritelock interface and its implementation class Reentrantreadwritelock

1.Lock & Reentrantlock

New Reentrantlock (); Lock.lock (); Try {    // Processing Task }catch(Exception ex) {     }finally{    Lock.unlock ();    // release Lock }

Reentrantlock is the only class that implements the lock interface. The use of lock must be done in the try-catch-finally block, and the action of releasing the lock is placed in the finally block to ensure that the lock must be released to prevent the deadlock from occurring. Lock must be manually released, the interrupt will not be automatically released, and the lock will be released automatically when the synchronized is interrupted.

2.ReadWriteLock & Reentrantreadwritelock

1  Public InterfaceReadwritelock {2     /**3 * Return the lock used for reading.4      */5 Lock Readlock ();6  7     /**8 * Return the lock used for writing.9      */Ten Lock Writelock (); One}

A read lock is a shared lock, and a write lock is an exclusive lock. If a thread has already occupied a read lock, the thread that is requesting a write lock waits for the read lock to be freed if the other thread is to request a write lock. If a thread has already occupied a write lock, the requested thread waits for the write lock to be released when another thread requests a write lock or read lock.

The use of the Wait ()/notify ()/Notifyall () method (how to wake up a blocked thread in Java?) )

In the history of Java, the suspend (), resume () method was used to wake up the thread, but there were a lot of problems, more typical or deadlock problem.

The solution can use blocking that targets objects, that is, using the Wait () and notify () methods of the object class to implement thread blocking.
First, the wait, notify method is for the object, and the Wait () method that calls any object will cause the thread to block, and the lock on the object will be released while blocking, and the Notify () method that calls any object will randomly dismiss the thread that the object is blocking. But it needs to regain the lock of the object until it succeeds, and second, the wait, notify method must be called in the synchronized Block or method, and ensure that the lock object of the synchronization block or method is the same as the object that calls the wait, notify method. As a result, the current thread has successfully acquired a lock on an object before calling wait, and when a wait block is executed, it releases the previously acquired object lock.

Iv. CAS (Hardware CPU synchronization Primitives)

1. How do I implement shared data access without locking mechanisms?

A common method of non-locking programming: Hardware CPU synchronization primitive CAs (Compare and Swap).

CAS is a non-blocking way of synchronizing. CAS implements an optimistic lock that differs from the sychronized synchronization lock, when multiple threads attempt to update the same variable using CAs, only one of the threads can update the value of the variable, and the other threads fail, and the failed thread is not suspended, but is told that the competition failed and can try again. The CAS has 3 operands, a memory value of V, an old expected value of a, and a new value, B, to be modified. 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.

  A variable that is shared among threads, first in main memory, and then a copy of the working memory of each thread is retained. The expected value here is the copy of the thread reservation. When the thread obtains the value of the variable from main memory, the variable in main memory may have been flushed by another thread, but the variable is still the original value in the working RAM of the thread, which is called the expected value. When you want to refresh the value with CAs, if you find that the thread working memory is inconsistent with main storage, it will fail, and if it is consistent, it can be updated successfully.

1  Public Final intIncrementandget () {2      for (;;) {3         intCurrent =get ();4         intNext = current + 1;5         if(Compareandset (current, next))6         returnNext;7     }8}

The CAS operation is used here, each time the data is read from memory and then the CAS operation is performed with the result of +1, if successful, the result is returned, otherwise it is retried until it succeeds.

First assume that there is a variable i,i initial value of 0. Each thread has a +1 operation on I. CAS is guaranteed to be synchronous: assuming there are two threads, thread 1 reads the value in memory as 0,current = 0,next = 1, then hangs, and then thread 2 operates on I, which turns the value of I into 1. Thread 2 executes, goes back to thread 1, enters if the Compareandset method, the logic of the operation of the method is, (1) If the value of the operand is not modified in memory, returns True, and then the Compareandset method returns to next Value (2) If the value of the operand is modified in memory, it returns false, re-enters the next loop, re-gets the value of current to 1,next value of 2, and then compares, because this time has not been modified, so directly return 2.

2. CAS Advantages and Disadvantages:

Advantage: CAS is highly efficient because it guarantees atomicity at the hardware level and does not lock the current thread.

Disadvantages:

1, long cycle time overhead. Spin CAs can cause very large CPUs if they are unsuccessful for a long time. Execution overhead. CAs are therefore not suitable for scenarios where competition is very frequent.

2. Only one atomic operation with a shared variable can be guaranteed. When performing operations on a shared variable, we can use circular CAs to guarantee atomic operations, but when working with multiple shared variables, the cyclic CAS cannot guarantee the atomicity of the operation, which can be done with locks.

Multi-threaded synchronization

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.