Java concurrent Programming display lock Reentrantlock and Readwritelock read-write lock _java

Source: Internet
Author: User
Tags finally block

Before Java5.0, only synchronized (built-in locks) and volatile. The display lock Reentrantlock is introduced after Java5.0.

Reentrantlock Overview

Reentrantlock is a reentrant lock, unlike a built-in lock, which needs to be displayed for lock and unlock every time it is used, and provides more advanced features: Fair locks, timed locks, conditional locks, polling locks, and broken locks. Can effectively avoid deadlocks in the active problem. Reentrantlock has realized

Lock interface:

Copy Code code as follows:

Public interface Lock {
Block until lock or interrupt is obtained
void Lock ();

Block until a lock is obtained or an interrupt throws an exception
void Lockinterruptibly () throws interruptedexception;

Only when the lock is available, it is returned directly
Boolean Trylock ();

Only if the lock is available at a specified time, otherwise it is returned directly, and the exception is thrown when interrupted
Boolean Trylock (long time, Timeunit unit) throws Interruptedexception;

void unlock ();

Returns a condition bound to this lock
Condition newcondition ();
}

Lock uses

Copy Code code as follows:

Lock lock = new Reentrantlock ();
Lock.lock ();
try{
Update Object state
}finally{
Notice here that there must be a finally block of code to unlock
Otherwise prone to deadlocks and other active problems
Lock.unlock ();
}


Reentrantlock characteristics

Polling lock and timing lock

A polling and a timed lock request is implemented through the Trylock () method and is not the same as an unconditional fetch lock. Reentrantlock can have flexible fault-tolerant mechanisms. Many deadlocks are caused by sequential locks, and different threads block when they attempt to acquire a lock, and do not release the lock they already hold, resulting in a deadlock. The Trylock () method, when trying to acquire a lock, if the lock is already held by another thread, it is returned immediately as set, instead of blocking all the time, and releasing its own lock after the return. You can retry or cancel according to the result returned, thereby avoiding the deadlock.

of fairness

The Reentrantlock constructor provides both fair and unjust locks (default). The so-called fair lock, the threads will acquire the lock in the order in which they make the request, and the queue is not allowed, but in an unfair lock, the queue is allowed: When a thread takes a request to acquire a lock, if the lock is available, the thread skips the queue waiting for the thread and acquires the lock. We generally hope that all locks are unfair. Because when you perform a lock operation, fairness will degrade performance significantly because of the overhead of thread suspend and recovery thread. Consider a situation where a thread holds a lock, and a B-thread requests the lock, so the b thread is suspended; a thread releases the lock, and the B thread wakes up, so try to acquire the lock again, while the C thread requests to acquire the lock, so C-Threading is likely to get, use, and release the lock before the B thread is fully awakened. It's a winning situation, B. The moment of acquiring a lock (b is awakened to acquire a lock) has not been postponed, C acquired the lock earlier, and the throughput has also been improved. In most cases, the performance of an unjust lock is higher than the performance of a fair lock.

Interruptible access to lock acquisition operation

The Lockinterruptibly method can maintain a response to interrupts while acquiring a lock, so there is no need to create other types of interruptible blocking operations.

Read and write lock Readwritelock

Reentrantlock is a standard mutex that can hold locks at most one thread at a time. Read-write locks are different, exposing two lock objects, one for read operations and one for write operations.

Copy Code code as follows:

Public interface Readwritelock {
/**
* Returns the lock used for reading.
*
* @return The lock used for reading.
*/
Lock Readlock ();

/**
* Returns the lock used for writing.
*
* @return The lock used for writing.
*/
Lock Writelock ();
}

You can choose to implement:

1. Release priority
2. Read Thread queue
3. Re-entry
4. Downgrade
5. Upgrade

The Reentrantreadwritelock implements the Readwritelock interface, and the constructor provides two ways to create fair and unjust locks. Read-write locks are suitable for situations where there is less reading, and better concurrency can be achieved.

Example

Copy Code code as follows:

public class Readwritemap<k, v> {
Private map<k, v> Map;
Private final Readwritelock lock = new Reentrantreadwritelock ();

Private final Lock Readlock = Lock.readlock ();
Private final Lock Writelock = Lock.writelock ();

Public Readwritemap (map<k, v> Map) {
This.map = map;
}

Public V get (K key) {
Readlock.lock ();
try {
return Map.get (key);
finally {
Readlock.unlock ();
}
}

public void put (K key, V value) {
Writelock.lock ();
try {
Map.put (key, value);
finally {
Writelock.unlock ();
}
}
}

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.