Java thread lock mechanism-synchronized lock Mutex read-write lock

Source: Internet
Author: User
Tags mutex

Synchronized is a mutual exclusion lock;

Lock is more extensive and includes read/write locks

Read/write Lock features:

1) Multiple readers can read at the same time
2) The writer must be mutually exclusive (only one writer is allowed to write, nor does the reader write at the same time)
3) The writer takes precedence over the reader (once the writer is written, the subsequent reader must wait, and the writer is given priority when waking)

Mutual exclusion Lock Features:

Only one thread at a time has a mutex, and the other thread waits only

The so-called mutex refers to a maximum of one thread holding a lock at a time. Before jdk1.5, we typically use the synchronized mechanism to control access to shared resources by multiple threads. And now, Lock provides a broader range of locking operations than the synchronized mechanism, the main difference between the lock and synchronized mechanisms:

The

ynchronized mechanism provides access to the implicit monitor locks associated with each object and forces all lock acquisition and deallocation to appear in a block structure,  when multiple locks are acquired,  they must be released in reverse order .  The synchronized mechanism's release of the lock is implicit, and the lock is freed as long as the thread runs out of the synchronized statement block range. The lock mechanism must explicitly invoke the Unlock () method of the lock object to release the lock, which provides the possibility that acquiring and releasing locks do not appear in the same block structure, and freeing the lock in a more liberal order .  The following code demonstrates acquiring and releasing locks in different block structures:

 Public class locktest {    privatestaticnew  reentrantlock ();      Public Static void Main (string[] args) {        lock.lock ();        InvokeMethod ();    }     Private Static void InvokeMethod () {        lock.unlock ();    }}

To ensure that the lock is released, the following code form is usually used:

New Reentrantlock (); // Get lock Lock.lock ();     Try {        //  access the resource protected by this lock    finally  {        /c13>//  release lock         lock.unlock ();    }

|--void Lock(): When this method is executed, the current thread acquires a lock if the lock is idle. Conversely, if the lock is already held by another thread, the current thread is disabled until the current thread acquires the lock.

|--void Unlock(): When this method is executed, the current thread will release the held lock. Locks can only be released by the holder, and if the thread does not hold the lock, execution of the method may cause an exception to occur.

    • Lock provides a non-block structure for acquiring a lock attempt--trylock (), an attempt to get an interruptible lock--lockinterruptibly (), and an attempt to obtain a timeout for a failed lock--trylock (long time, Timeunit unit).

|--boolean trylock(): If the lock is available, the lock is acquired and immediately returns true, otherwise false is returned. The difference between this method and lock () is that Trylock () simply "tries" to acquire the lock, and if the lock is not available, it does not cause the current thread to be disabled and the current thread continues to execute the code down. The lock () method is sure to get to the lock, and if the lock is not available, wait until the lock is not acquired and the current thread does not continue to execute down. The Trylock () method is typically called in the following code form:

   New Reentrantlock ();       if (Lock.trylock ()) {          try  {              //  manipulate protected state          finally  {              lock.unlock ();          }       Else {          //  perform alternative actions      }

This usage ensures that if a lock is acquired, the lock is released; If the lock is not acquired, it is not attempted to be freed.

Read-write lock--readwritelock interface and its implementation class Reentrantreadwritelock

The Reentrantreadwritelock defines 2 internal classes, Reentrantreadwritelock.readlock and Reentrantreadwritelock.writelock, which are used to represent both read and write locks, respectively. . The Reentrantreadwritelock object provides the Readlock () and Writelock () methods for acquiring read and write locks.

  • A read lock allows multiple reader threads to hold at the same time, while a write lock can have at most one writter thread.
  • Read-Write Lock usage: Reading shared data is much more frequent than modifying shared data. In these situations, concurrency performance can be improved by using read-write locks to control access to shared resources.
  • If a thread already holds a write lock, it can then hold a read-write lock. Conversely, if a thread already holds a read lock, it can no longer hold a write lock until the read lock is released.
  • The Newcondition () method that can call the write lock gets the condition object that is bound to the write lock, which is no different from the normal mutex. But the Newcondition () method that calls the read lock throws an exception. An example of using a read-write lock:
  •  Public classReadwritelocktest {Private StaticReadwritelock lock =NewReentrantreadwritelock (); Private StaticPerson person =NewPerson ("David Beckham",true);  Public Static voidMain (string[] args) {NewThread () { Public voidrun () { while(true) {                    Try{lock.readlock (). Lock (); System.out.print ("Name =" +person.getname ()); System.out.println (", Isman =" +Person.isman ()); } finally{lock.readlock (). Unlock ();        }                }            };        }.start (); NewThread () { Public voidrun () {BooleanState =true;  while(true) {                    Try{lock.writelock (). Lock (); if(state) {Person.setname ("Lady Gaga."); Person.setman (false); State=false; } Else{person.setname ("David Beckham"); Person.setman (true); State=true; }                                            } finally{lock.writelock (). Unlock ();        }                }            };    }.start (); }}classPerson {PrivateString name; Private BooleanIsman;  PublicPerson (String name,BooleanIsman) {         This. Name =name;  This. Isman =Isman; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public BooleanIsman () {returnIsman; }     Public voidSetman (BooleanIsman) {         This. Isman =Isman; }}

    Easy-to-understand experiments, reading and writing locks;

Java thread lock mechanism-synchronized lock Mutex read-write lock

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.