锁分离即采用多个锁。锁分离可以提升性能。
例1:
java.util.concurrent.LinkedBlockingQueue将队列头取出数据和队尾插入数据对应两个锁,而不是取出数据和插入数据抢占同一个锁。
/** Lock held by take, poll, etc */
private final ReentrantLock takeLock = new ReentrantLock();
/** Lock held by put, offer, etc */
private final ReentrantLock putLock = new ReentrantLock();
例2:
java.util.concurrent.locks.ReadWriteLock将读和写各对应一个锁。
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();
}
例2:
java.util.concurrent.ConcurrentHashMap的锁分离方式是将HashMap分段成多个Segment,每个Segment对应一个锁,即分段锁。