Java development package source code learning-AQS framework (I) Overview, javaaqs

Source: Internet
Author: User

Java development package source code learning-AQS framework (I) Overview, javaaqs

AQSActuallyjava.util.concurrent.locks.AbstractQueuedSynchronizerThis class. Read the Java concurrent package source code and you will find that this class is the wholejava.util.concurrentIt can also be said to be a breakthrough in reading the entire package source code.

For example, readReentrantLockSource code, you will find that its core is its internal classSync:

 

The structure of many classes in the entire package is like this, for exampleSemaphore,CountDownLatchEach has an internal classSyncAnd all syncs are inherited fromAbstractQueuedSynchronizer. So to read the Java and package code, you must first read this class.

AQSThe core of simplicity is to synchronize the State through a shared variable. The state of the variable is maintained by the subclass.AQSThe framework does the following:

  • Thread-blocking queue Maintenance
  • Thread blocking and Wakeup

Shared variables are modified throughUnsafeClass.AbstractQueuedSynchronizerThe main method of the class isacquireAndreleaseTypical template method. The following four methods are implemented by sub-classes:

protected boolean tryAcquire(int arg)protected boolean tryRelease(int arg)protected int tryAcquireShared(int arg)protected boolean tryReleaseShared(int arg)

AcquireThe method is used to obtain the lock. If the return value is true, the thread is successfully obtained and continues execution. If the return value is false, the thread is added to the waiting queue and is waiting to be awakened,ReleaseTo release the lock. In general, these two methods are encapsulatedlockAndunlockMethod.

The followingSimpleLockClass implements the simplest non-reentrant mutex lock function, in fact it isThreadPoolExecutor$Worker(This class will be mentioned later ).

class SimpleLock extends AbstractQueuedSynchronizer {    private static final long serialVersionUID = -7316320116933187634L;    public SimpleLock() {    }    protected boolean tryAcquire(int unused) {        if (compareAndSetState(0, 1)) {            setExclusiveOwnerThread(Thread.currentThread());            return true;        }        return false;    }    protected boolean tryRelease(int unused) {        setExclusiveOwnerThread(null);        setState(0);        return true;    }    public void lock() {        acquire(1);    }    public boolean tryLock() {        return tryAcquire(1);    }    public void unlock() {        release(1);    }    public boolean isLocked() {        return isHeldExclusively();    }}
Public static void main (String [] args) throws InterruptedException {final SimpleLock lock = new SimpleLock (); lock. lock (); for (int I = 0; I <10; I ++) {new Thread (new Runnable () {@ Override public void run () {lock. lock (); System. out. println (Thread. currentThread (). getId () + "acquired the lock! "); Lock. unlock ();}}). start (); // simply blocks the Thread on the lock according to the order of the for loop. sleep (100);} System. out. println ("main thread unlock! "); Lock. unlock ();}

Run the preceding test code and the result is as follows:

main thread unlock!9 acquired the lock!10 acquired the lock!11 acquired the lock!12 acquired the lock!13 acquired the lock!14 acquired the lock!15 acquired the lock!16 acquired the lock!17 acquired the lock!18 acquired the lock!

We will find that the waiting thread obtains the lock in sequence according to the blocking sequence. This is because AQS is based onCLH lock queueTo implement thread-blocking queues, we will briefly understand CLH lock queue in the next article.

Subsequent articles are planned as follows:

  • AQS framework for learning Java concurrent packet source code (2) CLH lock queue and spin lock
  • AQS framework for learning Java concurrent package source code (iii) LockSupport
  • Java concurrent packet source code learning-AQS framework (4) AbstractQueuedSynchronizer source code analysis
  • AQS framework (5) ConditionObject source code analysis of Java concurrent packet source code learning

......

  • Java concurrent packet source code learning lock (I) Overview
  • Lock for learning Java concurrent package source code (2) ReentrantLock source code analysis

......

  • Java concurrent package source code learning thread pool (I) Overview
  • Thread Pool (2) ThreadPoolExecutor source code analysis for Java concurrent packet source code learning

......

The original intention of learning the Java and package source code is to find out a problem that has been encountered before. In fact, I was planning to read the source code for a long time but I have never looked at it, therefore, you must look at the source code for a purpose rather than for a purpose.

 

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.