Java read-write lock

Source: Internet
Author: User

Display lock

Prior to java5.0, there were only synchronized and volatile mechanisms available to coordinate shared object access. Java5.0 adds a new mechanism: Reentrantlock. Reentrantlock is not an alternative to built-in locks, but is an optional advanced feature when built-in locks do not apply. Unlike the built-in lock, Lock provides an unconditional, polling, timed, and interruptible Lock acquisition operation, all of which are displayed with lock and unlock. In the implementation of lock, you must provide the same memory visibility semantics as the internal lock.

/**lock interface */public interface Lock {    void lock ();    void Lockinterruptibly () throws interruptedexception;    Boolean trylock ();    Boolean Trylock (long timeout,timeunit unit) throws interruptedexception;    void unlock ();    Condition newcondition ();}

Read/write Lock

Reetrantlock implements a standard mutex: at most one thread at a time can hold reetrantlock. For maintaining data integrity, mutual exclusion is an overly strong locking rule, so there is no need to limit concurrency. In many cases, the operations on the data structure are read operations. If you can relax the lock requirement and allow multiple threads of read operations to access the data structure at the same time, the performance of the program will be boosted. No problem occurs as long as each thread ensures that the latest data is read and no other thread modifies the data while it is being read. In this case, a read-write lock can be used: A resource can be accessed by multiple read operations, or accessed by a write operation, but not both.

/*readwritelock interface */public interface readwritelock{    Lock readlock ();    Lock Writelock ();}

The interaction between a read lock and a write lock can be implemented in a variety of ways. Some of the optional implementations in Readwritelock include:

    • release Priority . When a write operation releases a write lock, and there are both read and write threads in the queue, which thread should be selected first.
    • read thread queue . If the lock is held by a read thread, but the write thread is still waiting, is it permissible for the new read thread to gain access, or should it wait behind the write thread? If allowed, it can increase concurrency but may cause the write thread to starve.
    • re-enter the sex . Whether read and write locks can be re-entered.
    • downgrade and upgrade . If a thread holds a write lock can it acquire a read lock while continuing to hold a write lock? This may cause the write lock to "downgrade" to read lock. Does the read lock upgrade to a write lock prior to other waiting read and write threads? Upgrade is not supported in most read-write lock implementations because it is easy to deadlock (two read threads attempt to upgrade to write locks at the same time, neither will release write locks).

Reentrantreadwritelock provides reentrant semantics for both types of locks. Similar to Reentrantlock, Reentrantreadwritelock can be constructed with an optional non-fair lock (default) or a fair lock. In a fair lock, a thread that waits for a long time gets the lock first. If the lock is held by a read thread and another thread requests a write lock, other threads cannot obtain a read lock until the write lock is requested and freed after being used. In a non-fair lock, the order in which the thread obtains the lock is indeterminate. It is possible to downgrade a write thread to a read thread, which in turn cannot be (deadlock).

Similar to Reentrantlock, a write lock in Reentrantreadwritelock can have only one holder, and only the obtained thread is freed. A read lock in Java5.0 is more like a semaphore than a lock, it simply maintains the number of active read threads, regardless of their identity, so that it is not possible to distinguish whether a thread is the first request or a reentrant request, thus causing a fair read-write lock to deadlock. This implementation has been modified in JAVA6 to record which threads have received read locks.

/* Use a read/write lock to package Map*/public class Readwritemap<k, v> {    private final map<k, v> Map;    Private final Readwritelock lock = new Reentrantreadwritelock ();    Private final Lock R = Lock.readlock ();    Private final Lock w = Lock.writelock ();    Public Readwritemap (map<k, v> map) {        this.map = map;    }    Public V put (K key, V value) {        w.lock ();        try {            return Map.put (key, value);        } finally {            w.unlock ()}    }    The same operation is performed on the Remove (), Putall (), clear () method, public    V get (Object key) {        r.lock ();        try {            return Map.get (key);        } finally {            r.unlock ()}    }    Perform the same action on other read-only map methods}

When the lock is held for a long time and most of the read operation, the read-write lock can improve concurrency very well. The above program uses Reentrantreadwritelock to wrap the map so that it can be shared among multiple read threads. In reality Concurrenthashmap performance is good, if you need a concurrent hash-based mapping, then use CONCURRENTHASHMAP instead of this method. However, you can use this technique if you need to provide more concurrency access to another map implementation, such as Linkedhashmap.


Reference:

-Modern operating system

-Java Concurrent Programming combat

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.