Java的多线程安全是基于Lock机制(或者隐式锁synchronized)实现的,而Lock的性能往往不如人意。
原因是,monitorenter与monitorexit这两个控制多线程同步的bytecode原语,是JVM依赖操作系统互斥(mutex)来实现的。
互斥是一种会导致线程挂起,并在较短的时间内又需要重新调度回原线程的,较为消耗资源的操作。
为了优化Java的Lock机制,从Java6开始引入了轻量级锁的概念。
轻量级锁(Lightweight Locking)本意是为了减少多线程进入互斥的几率,并不是要替代互斥。
它利用了CPU原语Compare-And-Swap(CAS,汇编指令CMPXCHG),尝试在进入互斥前,进行补救。
这里先介绍第一种轻量级锁 自旋锁
自旋锁的原理是 让其他线程不断的循环等待着去用自身线程引用去加锁(当锁的竞争不大且,锁的时间段比较长的时候适用)
使用 AtomicReference 的方法 compareAndSet(V expect, V update):如果当前值 == 预期值,则以原子方式将该值设置为给定的更新值。
代码如下:
class SpinLock {
private AtomicReference<Thread> sign = new AtomicReference<Thread>();
public void lock() {
Thread current = Thread.currentThread();
//System.out.println(Thread.currentThread().getName() + " wait");
while (!sign.compareAndSet(null, current)) {
}
}
public void unlock() {
Thread current = Thread.currentThread();
sign.compareAndSet(current, null);
}
}
实例如下:
package thread;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLockTest {
private static int count = 0;
private static SpinLock spinLock = new SpinLock();
/**
* @param args
*/
@SuppressWarnings("static-access")
public static void main(String[] args) {
for (int i = 0; i < 100000; i++) {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
spinLock.lock();
count++;
spinLock.unlock();
}
});
thread.start();
}
System.out.println("here");
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count);
}
}
/**
* 自旋锁 让其他线程不断的循环等待着去用自身线程引用去加锁(当锁的竞争不大且,锁的时间段比较长的时候适用)。
*/
class SpinLock {
private AtomicReference<Thread> sign = new AtomicReference<Thread>();
public void lock() {
Thread current = Thread.currentThread();
//System.out.println(Thread.currentThread().getName() + " wait");
while (!sign.compareAndSet(null, current)) {
}
}
public void unlock() {
Thread current = Thread.currentThread();
sign.compareAndSet(current, null);
}
}
稍微面向对象点 是这样子的
package thread;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLockTest2 {
static int count = 100;
public static void main(String[] args) {
final SplinLock lock = new SplinLock();
for(int i=0;i<100;i++){
new Thread(new ThreadDemo(lock)).start();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count);
}
}
class ThreadDemo implements Runnable{
private SplinLock lock;
public ThreadDemo(SplinLock lock){
this.lock = lock;
}
@Override
public void run() {
lock.lock();
System.out.println(Thread.currentThread().getName()+"---"+SpinLockTest2.count);
SpinLockTest2.count--;
lock.unlock();
}
}
class SplinLock{
private AtomicReference<Thread> reference = new AtomicReference<Thread>();
public void lock(){
Thread thread = Thread.currentThread();
while(!reference.compareAndSet(null, thread)){
}
}
public void unlock(){
Thread thread = Thread.currentThread();
reference.compareAndSet(thread, null);
}
}