【问题标题】:unsafe.compareAndSwapInt first argument menanigunsafe.compareAndSwapInt 第一个参数含义
【发布时间】:2017-03-14 11:48:32
【问题描述】:

我正在调查java.util.concurrent.locks.AbstractQueuedSynchronizer源代码。

从多个地方调用compareAndSetState方法。

/**
 * Atomically sets synchronization state to the given updated
 * value if the current state value equals the expected value.
 * This operation has memory semantics of a {@code volatile} read
 * and write.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful. False return indicates that the actual
 *         value was not equal to the expected value.
 */
protected final boolean compareAndSetState(int expect, int update) {
    // See below for intrinsics setup to support this
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}

参数expectupdate很明显,对应原子参数。但是this 是对象(而不是int)。
这与expect相比如何?

【问题讨论】:

    标签: java concurrency synchronization atomic-swap


    【解决方案1】:

    它的字段state 将被CAS-ed 的实例。该值存储在该字段中。实例偏移对是一种将字段描述符转换为内存地址的方法,就像您在使用 Field::setField::getMethod::invoke 时需要提供实例一样。

    顺便说一句,这些 sun 课程的源代码可在 openjdk's mercury repository 在线获取。

    【讨论】:

    • AbstractQueuedSynchronizer 是如何产生价值的?
    • 这是AbstractQueuedSynchronizer::state 字段,而不是对象本身。
    • 实例偏移对它是什么?
    • 第一个和第二个函数参数。
    猜你喜欢
    • 1970-01-01
    • 2019-09-08
    • 2017-10-16
    • 2012-10-26
    • 1970-01-01
    • 2014-09-02
    • 2016-04-14
    • 2018-08-08
    • 2022-11-17
    相关资源
    最近更新 更多