LOCK基础
1 Lock原理
synchronized
关键字将会隐式地获取锁,但是将锁的获取和释放固化了,也就是先获取再释放。优点是简化了同步管理,缺点是扩展性没有锁的获取和释放来得好。
Lock lock = new ReentrantLock(); lock.lock();
try {
} finally {
lock.unlock(); }
在finally块中释放锁,目的是保证在获取到锁之后,最终能够被释放。不要将获取锁的过程写在try块中,因为如果在获取锁(自定义锁的实现)时发生了异常, 异常抛出的同时,也会导致锁无故释放。
两大块内容:
- 队列同步器AbstractQueuedSynchronizer(以下简称同步器)
- 以及常用Lock接口的实现ReentrantLock
Lock接口的实现基本都是通过聚合了一个同步器的子类来完成线程访问控制的。
可以这样理解二者之间的关系:
- 锁是面向使用者的,它定义了使用者与锁交 互的接口(比如可以允许两个线程并行访问),隐藏了实现细节;
- 同步器面向的是锁的实现者, 它简化了锁的实现方式,屏蔽了同步状态管理、线程的排队、等待与唤醒等底层操作。
锁和同步器很好地隔离了使用者和实现者所需关注的领域。
队列同步器AbstractQueuedSynchronizer(以下简称同步器),是用来构建锁或者其他同步组 件的基础框架,它使用了一个int成员变量表示同步状态,通过内置的FIFO队列来完成资源获 取线程的排队工作,并发包的作者(Doug Lea)期望它能够成为实现大部分同步需求的基础。重写同步器指定的方法时,需要使用同步器提供的如下3个方法来访问或修改同步状态:
- getState():获取当前同步状态。
- setState(int newState):设置当前同步状态。
- compareAndSetState(int expect,int update):使用CAS设置当前状态,该方法能够保证状态 设置的原子性。
同步器提供的模板方法基本上分为3类:
- 独占式获取与释放同步状态、
- 共享式获取与释放
- 同步状态和查询同步队列中的等待线程情况。
自定义同步组件将使用同步器提供的模板方法 来实现自己的同步语义。
2 重入锁ReentrantLock
重入锁ReentrantLock,顾名思义,就是支持重进入的锁,它表示该锁能够支持一个线程对
资源的重复加锁。除此之外,该锁的还支持获取锁时的公平和非公平性选择。
ReentrantLock
虽然没能像synchronized关键字一样支持隐式的重进入,但是在调用lock()方 法时,已经获取到锁的线程,能够再次调用lock()方法获取锁而不被阻塞。
事实上,公平的锁机制往往没有非公平的效率高,但是,并不是任何场景都是以TPS作为唯一的指标,公平锁能够减少“饥饿”发生的概率,等待越久的请求越是能够得到优先满足。
3 读写锁ReentrantReadWriteLock
ReentrantLock
是排他锁,这些锁在同一时刻只允许一个线 程进行访问,而读写锁
在同一时刻可以允许多个读线程访问,但是在写线程访问时,所有的读线程和其他写线程均被阻塞。
ReadWriteLock
仅定义了获取读锁和写锁的两个方法,即readLock()方法和writeLock()方法,而其实现——ReentrantReadWriteLock
。
4 Condition接口
Condition定义了等待/通知两种类型的方法,当前线程调用这些方法时,需要提前获取到 Condition对象关联的锁。Condition对象是由Lock对象(调用Lock对象的newCondition()方法)创 建出来的,换句话说,Condition是依赖Lock对象的。
获取一个Condition必须通过Lock的newCondition()方法。
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void conditionWait() throws InterruptedException {
lock.lock();
try {
condition.await();
} finally {
lock.unlock();
}
}
public void conditionSignal() throws InterruptedException { lock.lock();
try {
condition.signal(); } finally {
lock.unlock();
}
}
其他补充
1.Are Locks AutoCloseable?
https://stackoverflow.com/questions/6965731/are-locks-autocloseable
2 Hadoop中实现的AutoCloseableLock
想要用try-resource-with
,实现close
方法即可。
package org.apache.hadoop.util;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import com.google.common.annotations.VisibleForTesting;
/**
* This is a wrap class of a ReentrantLock. Extending AutoCloseable
* interface such that the users can use a try-with-resource syntax.
*/
public class AutoCloseableLock implements AutoCloseable {
private final Lock lock;
/**
* Creates an instance of {@code AutoCloseableLock}, initializes
* the underlying lock instance with a new {@code ReentrantLock}.
*/
public AutoCloseableLock() {
this(new ReentrantLock());
}
/**
* Wrap provided Lock instance.
* @param lock Lock instance to wrap in AutoCloseable API.
*/
public AutoCloseableLock(Lock lock) {
this.lock = lock;
}
// 定义一个获取锁的方法
public AutoCloseableLock acquire() {
lock.lock();
return this;
}
//释放锁
public void release() {
lock.unlock();
}
//close方法是必须的
@Override
public void close() {
release();
}
/**
* A wrapper method that makes a call to {@code tryLock()} of
* the underlying {@code Lock} object.
*
* If the lock is not held by another thread, acquires the lock, set the
* hold count to one and returns {@code true}.
*
* If the current thread already holds the lock, the increment the hold
* count by one and returns {@code true}.
*
* If the lock is held by another thread then the method returns
* immediately with {@code false}.
*
* @return {@code true} if the lock was free and was acquired by the
* current thread, or the lock was already held by the current
* thread; and {@code false} otherwise.
*/
public boolean tryLock() {
return lock.tryLock();
}
/**
* A wrapper method that makes a call to {@code isLocked()} of
* the underlying {@code ReentrantLock} object.
*
* Queries if this lock is held by any thread. This method is
* designed for use in monitoring of the system state,
* not for synchronization control.
*
* @return {@code true} if any thread holds this lock and
* {@code false} otherwise
*/
@VisibleForTesting
boolean isLocked() {
if (lock instanceof ReentrantLock) {
return ((ReentrantLock)lock).isLocked();
}
throw new UnsupportedOperationException();
}
/**
* See {@link ReentrantLock#newCondition()}.
* @return the Condition object
*/
public Condition newCondition() {
return lock.newCondition();
}
}