ReentrantLock如何同步?

时间:2012-04-27 13:51:34

标签: java multithreading synchronization reentrantlock

我查看了ReentrantLock的Java API,我看到的是synchronized关键字没有使用同步。它是在AbstractQueuedSynchronizer中的下面方法(ReentrantLock在尝试获取锁时引用的)同步对象吗?由于compareAndSwapInt是本机方法,因此是在本机级别/代码进行同步吗?

protected final boolean compareAndSetState(int expect, int update) {
    // See below for intrinsics setup to support this
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

2 个答案:

答案 0 :(得分:3)

每个JDK的实现可能会有所不同。例如,Sun(现在的Oracle)实现通过sun.misc.Unsafehttp://www.docjar.com/docs/api/sun/misc/Unsafe.html

来实现

我曾在博客上写过Java concurrency in unsafe:)

答案 1 :(得分:1)

你是对的:在Oracle的JDK中,ReentrantLock是根据本机compare-and-swap原语(加上相当数量的Java代码)实现的,而不是在synchronized关键字。