Java structured lock vs unstructured lock

Source: Internet
Author: User

What is structured lock? First snippet Code:

synchronized Boolean contains (final Integer object) {        Entry pred = this.head;        Entry Curr = Pred.next;        while (Curr.object.compareTo (object) < 0) {            pred = Curr;            Curr = Curr.next;        }        return Object.Equals (Curr.object);    }

This code uses synchronized to solve the concurrency problem, this example is the lock on the method, that is, the object level, then once the object is locked, all the synchronization methods of the object will be locked, the time when the lock is released is the method execution, Mention synchronized, also incidentally mention wait/notify good, see the following code:

public class Main {public    static void Main (string[] args) {        threadb b = new threadb ();        B.start ();        Synchronized (b) {            try{                System.out.println ("Waiting for B to complete ...");                B.wait ();            } catch (Interruptedexception e) {                e.printstacktrace ();            }            SYSTEM.OUT.PRINTLN ("Total is:" + B.total);}}    Class THREADB extends thread{    int total;    @Override public    Void Run () {        synchronized (this) {            try {                sleep ()            } catch ( Interruptedexception e) {                System.out.println ("Wokao");            }            for (int i=0; i<100; i++) {Total                + = i;            }            Notify ();}}}    

(this program generally runs without problems, but there is a potential bug, who can see it) combined with this example, two sentences can basically explain

    1. wait()Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls Notify ().
    2. notify()Wakes up the first thread, the called on the wait() same object.

This synchronized to the synchronization mechanism, also known as structured lock, because it looks very structured, very structured there?

But results are not flexible enough to respond to results. When does it need to be flexible? As an example,

There's a list of a->b->c->d->e->f.

Suppose the next set of work:

1. Write A and B;

2. Write B and C

3. Write C and D

4. Write D and E

5. Write E and F

If you lock A and B in 1 with synchronized, then 2 must wait for both A and B to perform, but is it necessary? In fact, as long as a end, 2 should be able to execute, in turn, this is called hand in hand locking,

is a chain lock, described as follows:

Lock A and B, start Job 1

Unlock A, lock C, start Job 2

Unlock B, lock D, start Job 3 ...

This kind of chain lock, obviously synchronized cannot do, sychronized inside can set other synchronized, that can only form a nested structure.

This is the limitation of synchronized, or structured lock.

So in this case unstructured lock is useful, see an example of use:

public static final class Coarselist extends Listset {/* * TODO Declare a lock for this class to be used I         n Implementing the * Concurrent Add, remove, and contains methods below.        */Reentrantlock lk= new Reentrantlock ();         /** * Default constructor.        */Public Coarselist () {super ();         }/** * {@inheritDoc} * * TODO use a lock to protect against concurrent access.                */@Override Boolean Add (Final Integer object) {try{lk.lock ();                Entry pred = This.head;                Entry Curr = Pred.next;                    while (Curr.object.compareTo (object) < 0) {pred = Curr;                Curr = Curr.next;                } if (Object.Equals (Curr.object)) {return false;                  } else {final Entry Entry = new Entry (object);  Entry.next = Curr;                    Pred.next = entry;                return true;            }}finally {Lk.unlock (); }        }

  

Reentrantlock here is very flexible, but must be explicitly unlock, otherwise there will be a problem (as C + + must display the same as delete memory), in order to prevent accidents such as throwing exception, you should put the unlock statement in Finally, So here's the drawbacks must be able to see it, everywhere to write a try finally statement!!!

Unstructured lock also has a benefit to distinguish between read and write locks, theoretically multiple threads read no problem, so with a weak read-write lock, and once a thread is written, the other threads will be aware that only one thread can be written on the locked object, when other threads read or write, All have to wait. above example:

public static final class Rwcoarselist extends Listset {/* * TODO Declare a read-write lock for this class         To being used in * implementing the concurrent Add, remove, and contains methods below.         *//** * Default constructor.        */Public Rwcoarselist () {super ();         }/** * {@inheritDoc} * * TODO use a read-write lock to protect against concurrent access.        */Reentrantreadwritelock Rwlk = new Reentrantreadwritelock ();                @Override Boolean Add (Final Integer object) {try {rwlk.writelock (). Lock ();                Entry pred = This.head;                Entry Curr = Pred.next;                    while (Curr.object.compareTo (object) < 0) {pred = Curr;                Curr = Curr.next;                } if (Object.Equals (Curr.object)) {return false;              } else {      Final Entry Entry = new Entry (object);                    Entry.next = Curr;                    Pred.next = entry;                return true;            }}finally {Rwlk.writelock (). Unlock (); }        }

  

Not yet, unstructured Lock's third advantage is that support trylock, look at the name can be seen, is to try to take the lock, do not get, do other things. Think about how synchronized did it, try to get the lock first, not get it, block! Stand up for the award

Java structured lock vs unstructured lock

Related Article

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.