Xi. locks in the Juc package

Source: Internet
Author: User
Tags cas

JUC, namely java.util.concurrent.

Pessimistic lock and optimistic lock

Pessimistic locking and optimistic locking is an idea.

Pessimistic lock, holding a pessimistic attitude, think there will be a very bad situation, so, first to do preventive measures. An exclusive lock is a pessimistic lock, and synchronized is an exclusive lock.

The optimistic lock, is holding a kind of optimistic attitude, think there will not be any problems, there are problems to say.

For common multithreaded programming people estimate know that before JDK5, in multithreaded programming, in order to ensure that multiple threads on an object at the same time access, we need to add a synchronous lock synchronized, to ensure the correctness of the object in use, but the locking mechanism will lead to the following problems

1. With multi-threaded competition, locking and releasing locks can lead to more context switching, causing performance problems.

2. Multithreading can cause a deadlock problem.

3. Multiple threads holding a lock can cause the other thread that needs this lock to hang.

4 ...

CAS (Compare and swap) lock-free algorithm: English full Name translation = = comparison and exchange, is a non-blocking lock-free algorithm. Since it is nothing, thread blocking is not possible. The semantics of CAS is "I think the value of V should be a, if it is, then update the value of V to B, otherwise do not modify and tell the value of V is actually how much", CAS is an optimistic locking technique, when multiple threads try to update the same variable simultaneously using CAS, only one of the threads can update the value of the variable, and the , the failed thread is not suspended, but is told that the competition has failed and can try again. 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.

I've been in a peer-to-peer system, and many parts of the system are based on the versioning mechanism. That is, to add a version of the data to identify, generally in the table added a version field, read out the data, the version number is read together, then update, the version number is compared, if the current version number is consistent with the database, the data (version field to add 1 operation) to update, otherwise, The data is considered out of date and not processed.

Spin locks : Spin locks are similar to mutex locks, and they are all designed to resolve mutually exclusive use of a resource. Whether it is a mutex or a spin lock, there can be at most one hold at any time, and it is said that at most one execution unit can acquire a lock at any time. But the two are slightly different in the scheduling mechanism. For mutexes, resource applicants can only go to sleep if the resource is already occupied. But the spin lock does not cause the caller to sleep, and if the spin lock has been held by another execution unit, the caller has been circulating there to see if the spin lock has released the lock and the word "spin" is named.

Juc the lock in the package

The lock in the JUC package is more powerful than a sync lock, and it provides a framework for locks that allow for more flexibility in using locks, but it is even more difficult to use.

Juc lock in package, including: Lock interface, Readwritelock interface, Locksupport blocking primitives, condition conditions, abstractownablesynchronizer/ Abstractqueuedsynchronizer/abstractqueuedlongsynchronizer three abstract classes, Reentrantlock exclusive locks, Reentrantreadwritelock read and write locks. Since Countdownlatch,cyclicbarrier and semaphore are also implemented through AQS, I also introduce them into the framework of locks.

Look at the lock's frame diagram first, as shown below.

The. Lock interface

The lock interface in the JUC package supports locking rules that differ in semantics (re-entry, fairness, and so on). The so-called semantic differences, refers to the lock is a "fair mechanism of the lock", "non-fair mechanism of the lock", "reentrant lock" and so on. "Fairness mechanism" refers to "the mechanism of acquiring locks by different threads is fair", while "unfair mechanism" means "the mechanism of acquiring locks by different threads is unfair", "reentrant lock" means that the same lock can be acquired multiple times by a thread.

Readwritelock.

The Readwritelock interface defines a lock in a manner similar to lock that some readers can share while the writer is exclusive. JUC package only one class implements the interface, that is, Reentrantreadwritelock, because it applies to most of the standard usage contexts. But programmers can create their own implementations that apply to non-standard requirements.

Abstractownablesynchronizer/abstractqueuedsynchronizer/abstractqueuedlongsynchronizer.
Abstractqueuedsynchronizer is called the AQS class, which is a very useful superclass that can be used to define locks and other synchronizers that rely on queued blocking threads; Reentrantlock, These classes, such as Reentrantreadwritelock,countdownlatch,cyclicbarrier and semaphore, are implemented based on the Aqs class. The Abstractqueuedlongsynchronizer class provides the same functionality but extends support for 64 bits of the synchronization state. Both extend the class Abstractownablesynchronizer, a simple class that helps to record threads that are currently holding exclusive synchronizations.


Locksupport.
Locksupport provides "create locks" and "basic thread blocking primitives for other synchronization Classes".
Locksupport's functionality is somewhat similar to the Thread.Suspend () and Thread.Resume () in Thread, where Park () and Unpark () in Locksupport are blocking threads and unblocking threads, respectively. However, Park () and Unpark () do not encounter the "deadlock that may be caused by thread.suspend and thread.resume" issues.

Condition.
Condition needs to be used in conjunction with lock, which acts as a substitute for the object monitor method, and can hibernate/wake the thread through await (), signal ().
The Condition interface describes the condition variables that may be associated with a lock. These variables are similar in usage to implicit monitors that use object.wait access, but provide more powerful functionality. It should be noted that a single Lock may be associated with multiple Condition objects. To avoid compatibility issues, the name of the Condition method differs from the corresponding Object version.

Reentrantlock.
Reentrantlock is an exclusive lock. The so-called exclusive lock, refers to only be occupied alone, that is, the same point in time can only be acquired by a thread lock. Reentrantlock locks include "fair reentrantlock" and "non-fair reentrantlock". "Fair reentrantlock" means that "the mechanism by which different threads acquire locks is fair", while "unfair reentrantlock" means "the mechanism by which different threads acquire locks is unfair" and reentrantlock are "reentrant locks".
The UML class diagram for Reentrantlock is as follows:

(Reentrantlock) implements the lock interface.
Reentrantlock has a member variable sync,sync is the sync type; sync is an abstract class, and it inherits from Aqs.
There are "fair lock class" Fairsync and "unfair lock class" Nonfairsync in Reentrantlock, all of which are subclasses of sync. The Sync object in Reentrantreadwritelock is one of the Fairsync and Nonfairsync, which means that Reentrantlock is one of the "fair locks" or "unfair locks", Reentrantlock default is a non-fair lock.

. reentrantreadwritelock
Reentrantreadwritelock is the implementation class for the read-write lock interface Readwritelock, which includes subclasses Readlock and Writelock. Reentrantlock is a shared lock, while Writelock is an exclusive lock.
The UML class diagram for Reentrantreadwritelock is as follows:


Reentrantreadwritelock implements the Readwritelock interface.
The Reentrantreadwritelock contains Sync objects, read-lock ReaderLock, and write-lock WriterLock. Both the read lock Readlock and the write lock Writelock implement the lock interface.
(03) Like "Reentrantlock", Sync is the sync type, and sync is an abstract class that inherits from Aqs. Sync also includes "fair lock" Fairsync and "unfair lock" nonfairsync.


Countdownlatch.
Countdownlatch is a synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed.
The UML class diagram for Countdownlatch is as follows:


The countdownlatch contains the Sync object, and sync is the sync type. Countdownlatch's sync is the instance class, which inherits from Aqs.

Cyclicbarrier.
Cyclicbarrier is a synchronous helper class that allows a group of threads to wait for each other until a common barrier point (common barrier points) is reached. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier.
The UML class diagram for Cyclicbarrier is as follows:


Cyclicbarrier is the "Reentrantlock object lock" and "condition Object Trip", which is implemented by an exclusive lock.
  the difference between Cyclicbarrier and Countdownlatch is:
Countdownlatch's role is to allow 1 or n threads to wait for other threads to complete execution, while Cyclicbarrier allows n threads to wait for each other.
Countdownlatch counters cannot be reset, cyclicbarrier counters can be reset and used, so it is called a circular barrier.

Ten. Semaphore
Semaphore is a count semaphore, and its essence is a "shared lock".
The semaphore maintains a semaphore license set. A thread can obtain a semaphore's license by calling acquire (), and the thread can obtain the license when there is a license available in the semaphore, otherwise the thread must wait until a license is available. The thread can release () The semaphore license it holds.
The UML class diagram for semaphore is as follows:


Like "Reentrantlock", Semaphore contains the Sync object, Sync is the sync type, and sync is an abstract class that inherits from Aqs. Sync also includes "fair semaphore" Fairsync and "non-fair semaphore" Nonfairsync.

------More please refer to "Java Multithreading Series-" JUC lock "01 framework"

Concurrent

Xi. locks in the Juc package

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.