java 锁的类型_Java锁的种类 - shawnplaying的个人页面 - OSCHINA - 中文开源技术交流社区...

Java锁和并发需要结合在一块了理解,涉及到了多个话题。

本文主要参考了 http://ifeve.com/java_lock_see1/ 但是我认为原文中有某些错误,我在下面的代码中做了修改。

公平锁和非公平锁。

所谓公平锁,就是多个线程解锁的顺序与进入锁的顺序一样,即谁先锁,谁就先解锁。反之则是非公平锁。例如ReentrantLock中就有公平与非公平两种锁实现,默认是非公平锁。

public ReentrantLock() {

sync = new NonfairSync();

}

下面讨论几种锁:

1 自旋锁。所谓自旋,就是在一个循环中处理。例如:

//AtomicInteger

public final int getAndIncrement() {

for (;;) {

int current = get();

int next = current + 1;

if (compareAndSet(current, next))

return current;

}

}

//AtomicReference

public final V getAndSet(V newValue) {

while (true) {

V x = get();

if (compareAndSet(x, newValue))

return x;

}

}

/**

* 自旋锁,会不停地在循环中获取值,这种方式会耗尽CPU。

* 原子类中很多方法都采用了类似的循环方法,这种方法我觉得适用于执行时间很短的操作。

* 例如在原子类中getAndDecrement等方法,都是采用了循环的方式取值,这种操作虽然用了循环,但是每次操作瞬间完成,总体上讲应该不会特别耗费CPU资源。

*

*

* 总之不能让线程中的代码长时间在一个什么都不做的循环中,例如while(true){},不然CPU资源会被耗尽。

*

* @author zhaoxp

*

*/

public class SpinLock {

private AtomicReference sign =new AtomicReference<>();

public void lock(){

Thread current = Thread.currentThread();

while(!sign .compareAndSet(null, current)){

}

}

public void unlock (){

Thread current = Thread.currentThread();

sign .compareAndSet(current, null);

}

}

自旋的问题在一直在执行循环,这样会导致CPU使用率高的问题。在windows的服务器上实测,开启50个线程(线程数量超过CPU的核数),会导致每个CPU核都达到100%的使用率,所以这就意味着这种方法不是一个可用的方法,尤其并发任务重的时候。

同样的场景,如果使用ReentrantLock的话,CPU是很低的,所以ReentrantLock是一个很好的选择。

当时对于SpinLock,如果在lock的循环中加入Thread.sleep(1000)的话,运行时CPU很低,所以如果没有时效性要求,那么自旋的方式还是可以使用。

另外还有三种自旋锁:TicketLock,CLHLock,MCSLock。

import java.util.concurrent.atomic.AtomicInteger;

public class TicketLock {

private AtomicInteger                     serviceNum = new AtomicInteger();

private AtomicInteger                     ticketNum  = new AtomicInteger();

private static final ThreadLocal LOCAL      = new ThreadLocal();

public void lock() {

int myticket = ticketNum.getAndIncrement();

LOCAL.set(myticket);

while (myticket != serviceNum.get()) {

}

}

public void unlock() {

int myticket = LOCAL.get();

serviceNum.compareAndSet(myticket, myticket + 1);

}

}

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class CLHLock {

public static class CLHNode {

private volatile boolean isLocked = true;

}

@SuppressWarnings("unused")

private volatile CLHNode                                           tail;

private static final ThreadLocal                          LOCAL   = new ThreadLocal();

private static final AtomicReferenceFieldUpdater UPDATER = AtomicReferenceFieldUpdater.newUpdater(CLHLock.class,CLHNode.class, "tail");

public void lock() {

CLHNode node = new CLHNode();

LOCAL.set(node);

CLHNode preNode = UPDATER.getAndSet(this, node);

if (preNode != null) {

//preNode==null means it is first node;

while (preNode.isLocked) {// the other threads all stopped here

//并发操作的线程都将运行在这段代码,它是非常耗费CPU资源的操作。

}

preNode = null;

LOCAL.set(node);

}

}

public void unlock() {

CLHNode node = LOCAL.get();

if (!UPDATER.compareAndSet(this, node, null)) {

//这个if判断的作用是:如果只有一个lock操作,那么if中的判断应该为false,同时它意味着没有并发。

//如果同时有多于一个lock操作,那么if将返回true,则执行if中的操作。同时它表示有并发。

node.isLocked = false;

}

node = null;

}

}

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class MCSLock {

public static class MCSNode {

volatile MCSNode next;

volatile boolean isLocked = true;

}

private static final ThreadLocal                          NODE    = new ThreadLocal();

@SuppressWarnings("unused")

private volatile MCSNode                                           queue;

private static final AtomicReferenceFieldUpdater UPDATER = AtomicReferenceFieldUpdater.newUpdater(MCSLock.class,MCSNode.class, "queue");

public void lock() {

MCSNode currentNode = new MCSNode();

NODE.set(currentNode);

MCSNode preNode = UPDATER.getAndSet(this, currentNode);

if (preNode != null) {

preNode.next = currentNode;

while (currentNode.isLocked) {

}

}

}

public void unlock() {

MCSNode currentNode = NODE.get();

if (currentNode.next == null) {

if (UPDATER.compareAndSet(this, currentNode, null)) {

//最后一个node,并且在操作时再也没有追加node

} else {

//最后一个node,但是在操作时追加node

while (currentNode.next == null) {

//等待后追加的node做preNode.next=node的操作。也就是等待后追加的node设置当前node的next node值。

}

}

} else {

currentNode.isLocked = false;

currentNode.next = null;

}

}

}

这三种自旋锁的具体实现中,虽然代码上没有链表或者队列的数据结构,但是实际从本质上讲,它们就是链表或者队列的结构。通过ThreadLocal等的精巧的数据结构实现。

这里的链表的实现,关键在于:

<1> 使用了原子类中的getAndSet方法,这个实现了线程安全的得到老值,设置新值。

<2> 使用了ThreadLocal保存getAndSet中得到的老值。

2 阻塞锁。基于上面提到的CLHLock锁,与之不同的是,它使得线程的状态发生变化,因为使用了LockSupport.park(this);和LockSupport.unpark(node.isLocked)的方法。

还有,我理解的synchronized语句,其实也是起到了阻塞锁的作用。

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

import java.util.concurrent.locks.LockSupport;

public class CLHLock1 {

public static class CLHNode {

private volatile Thread isLocked;

}

@SuppressWarnings("unused")

private volatile CLHNode                                            tail;

private static final ThreadLocal                           LOCAL   = new ThreadLocal();

private static final AtomicReferenceFieldUpdater UPDATER = AtomicReferenceFieldUpdater.newUpdater(CLHLock1.class,CLHNode.class, "tail");

public void lock() {

CLHNode node = new CLHNode();

LOCAL.set(node);

CLHNode preNode = UPDATER.getAndSet(this, node);

if (preNode != null) {

preNode.isLocked = Thread.currentThread();

LockSupport.park(preNode.isLocked);//降低CPU使用率

preNode = null;

LOCAL.set(node);

}

}

public void unlock() {

CLHNode node = LOCAL.get();

if (!UPDATER.compareAndSet(this, node, null)) {

System.out.println("unlock\t" + node.isLocked.getName());

LockSupport.unpark(node.isLocked);//降低CPU使用率

}

node = null;

}

}

3 可重入锁,也叫递归锁。“指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响。”

比如CLHLock中,如果做两次 lock.lock()操作,即使有两次unlock操作,程序依然有问题将进入死循环。

在JAVA环境下 ReentrantLock 和synchronized 都是 可重入锁。

修改CLHLock,将它改进为可重入锁:

public class SpinLock1 {

private AtomicReference owner =new AtomicReference<>();

private int count =0;

public void lock(){

Thread current = Thread.currentThread();

if(current==owner.get()) {

count++;

return ;

}

while(!owner.compareAndSet(null, current)){

}

}

public void unlock (){

Thread current = Thread.currentThread();

if(current==owner.get()){

if(count!=0){

count--;

}else{

owner.compareAndSet(current, null);

}

}

}

}

综合来说,各种锁都有其用处。

1 对于高并发,要使用可重入锁,推荐ReentrantLock。

2 自旋锁可以进行扩展来实现更多功能功能。比如在等待中加入其它操作。这个值得再思考。

3 以后想起再补充吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值