"The Art of Java concurrent programming" lock in--java

Source: Internet
Author: User

NO1:

Lock interface

New Reentrantlock (); Lock.lock (); Try {}finally{    lock.unlock ();}

No2:

Do not say the process of acquiring a lock is written in a try block, because if an exception occurs while acquiring the lock (the implementation of the custom lock), the exception is thrown, causing the lock to be released for no reason

No3:

No4:

The queue Synchronizer (synchronizer) is the underlying framework used to build a lock or other synchronization component that uses an INT member variable to represent the synchronization state, to complete the queued work of the resource acquisition thread through the built-in FIFO queue, and the author of the contract expects it to be the basis for most of the synchronization requirements.

The primary use is inheritance, which manages the synchronization state by inheriting the Synchronizer and implementing its abstract method.

NO5:

The lock is intended for the consumer, which defines the interface to which the user interacts with the lock (for example, allowing two threads to access concurrently), hiding the implementation details

Synchronizer is oriented to the implementation of the lock, which simplifies the implementation of the lock, shielding the synchronization state management, thread queuing, wait and wake, and other underlying operations.

Locks and Synchronizers are a good way to isolate the areas of concern for both the user and the person who implements it.

NO6:

The template method provided by the Synchronizer is basically divided into 3 categories:

1) exclusive acquisition and release synchronization status

2) shared capture and release sync status

3) Querying waiting threads in the synchronization queue

No7:

Exclusive lock: Only one thread acquires the lock at the same time, while the other thread that acquires the lock can only wait in the synchronization queue, and only the thread that acquires the lock releases the lock, and the subsequent line friend can acquire the lock.

classMutexImplementslock{//static inner class, custom Synchronizer    Private Static classSyncextendsabstractqueuesynchronizer{//Is in a occupied State        protected Booleanisheldexclusively () {returnGetState () = = 1; }        //acquires a lock when the status is 0         Public BooleanTryacquire (intacquires) {            if(Compareandsetstate (0,1) {setexclusiveownerthread (Thread.CurrentThread ()); return true; }            return false; }        //Release the lock, set the status to 0        protected BooleanTryrelease (intrelease) {            if(getState () = = 0)Throw Newillegalmonitorstateexception (); Setexclusiveownerthread (NULL); SetState (0); return true; }        //returns a condition with each condition containing a condition queueCondition newcondition () {return NewCondition (); }    }    //only need to delegate the operation to sync    Private FinalSync sync =NewSync ();  Public voidLock () {Sync.acquire (1)};  Public BooleanTrylock () {returnSync.tryacquire (1); }     Public voidunlock () {Sync.release (1); }     PublicCondition newcondition () {returnsync.newcondition (); }     Public BooleanisLocked () {returnsync.isheldexclusively (); }     Public Booleanhasqueuedtreads () {returnsync.hasqueuedtreads (); }     Public voidLockinterruptibly ()throwsinterruptedexception{sync.acquireinterruptibly (1); }     Public BooleanTrylock (LongTimeout,timeunit unit)throwsinterruptedexception{returnSync.tryacquirenanos (1, Unit.tonanos (timeout)); }}

No8:

Re-entering the lock Reentrantlock, is to support the re-entry lock, which indicates that the lock can support a thread of the resource repeatedly lock. In addition, the lock also supports the choice of fair and non-fairness when acquiring locks

No9:

Re-entry means that any thread can acquire the lock again after acquiring the lock without being blocked by the lock, the implementation of this feature needs to address the following two issues

1) The thread acquires the lock again. The lock needs to identify if the thread that gets the lock is the thread that currently occupies the lock, and if it is, succeeds in getting

2) The final release of the lock. The thread repeats n times acquires the lock, and then the other thread acquires the lock after the nth release of the lock. The final release of the lock requires that the lock be counted for gain, the count indicates the number of times the current lock has been repeatedly fetched, while the lock is freed, the count is reduced, and when the count equals 0, the lock has been successfully released

Final BooleanNonfairtryacquire (intacquires) {    FinalThread current =Thread.CurrentThread (); intc =getState (); if(c = = 0){        if(Compareandsetstate (0, acquires))            {Setexclusiveownerthread (current); return true; }    }Else if(Current = =Getexclusiveownerthread ()) {        intNEXTC = C +acquires; if(NEXTC <0){            Throw NewError ("Maximum Lock count Exceeded");        } setState (NEXTC); return true; }    return false;}protected Final BooleanTryrelease (intrelease) {    intc = getState ()-release; if(Thread.CurrentThread ()! =Getexclusiveownerthread ()) {        Throw Newillegalmonitorstateexception (); }    BooleanFree =false; if(c = = 0) { free=true; Setexclusiveownerthread (NULL);    } setState (c); returnFree ;}

No10:

Exclusive and Reentrant locks are exclusive locks that allow only one thread to access at the same time.

The read-write lock Reentrantreadwritelock can allow multiple read threads at the same time, but all read threads and other threads are blocked when the write thread accesses.

Read-write lock maintains a pair of locks, a read lock and a write lock, by separating the read and write locks, so that concurrency compared to the general exclusive lock has a great increase

 Public classcache{Staticmap<string,object> map =NewHashmap<string,object>(); StaticReentrantreadwritelock RWL =NewReentrantreadwritelock (); StaticLock r =Rwl.readlock (); StaticLock W =Rwl.writelock (); //gets the value corresponding to a key     Public Static FinalObject get (String key) {R.lock (); tyr{returnMap.get (key); }finally{r.unlock (); }    }    //sets the value of the key and returns the old value     Public Static FinalObject put (String key,object value) {W.lock (); Try{            returnMap.put (Key,value); }finally{w.unlock (); }    }    //Clear all the contents     Public Static Final voidClear () {w.lock (); Try{map.clear (); }finally{w.unlock (); }    }}

When a write lock is acquired, other threads are blocked from acquiring read and write locks, and other read and write operations can continue only after the write lock is freed.

NO11:

A read lock is a shared lock that supports re-entry, which can be acquired by multiple threads at the same time, and when no other write threads are accessed, the read lock is always successfully fetched, and only the (thread-safe) read state is added.

No12:

Lock demotion refers to the write lock demotion as a read lock. Refers to the process of holding (currently owned) a write lock, acquiring a read lock, and then releasing (previously owned) a write lock.

 Public voidProcessData () {readlock.lock (); if(!update) {        //read lock must be released firstReadlock.unlock (); //Lock demotion from write lock acquisition to startWritelock.lock (); Try{            if(!update) {                //process for preparing data (a little)Update =true;        } readlock.lock (); }finally{writelock.unlock (); }        //Lock demotion Complete, write lock degraded to read lock    }    Try{        //process of using data (slightly)}finally{readlock.unlock (); }}

No12:

Rentrantreadwritelock does not support lock escalation (the process of holding a read lock, acquiring a write lock, and finally releasing a read lock). The goal is also to ensure data visibility, if a read lock has been acquired by multiple threads, where any thread has successfully acquired a write lock and updated the data, its update is not visible to other threads that acquire a read lock.

NO13:

NO14:

Condition defines a wait/notification type of method that, when called by the current thread, needs to get the lock associated with the condition object in advance. The condition object is created by the lock object (called the Newcondition () method of the lock object), in other words, the condition is dependent on the lock object's

Lock lock =NewReentranlock (); Condition Condition=lock.newcondition (); Public voidConditionwait ()throwsinterruptedexception{Lock.lock (); Try{condition.await (); }finally{lock.unlock (); }} Public voidConditionsignal ()throwsinterruptedexception{Lock.lock (); Try{condition.signal (); }finally{lock.unlock (); }}

NO15:

Conditionobject is the inner class of the Synchronizer Abstractqueuedsynchronizer, because the condition operation needs to acquire the associated lock, so the inner class as the Synchronizer is also more reasonable. Each condition object contains a queue that is the key to the condition object to implement the wait/Notify feature.

"The Art of Java concurrent programming" lock in--java

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.