Kotlin同步inine

enl*_*now 2 kotlin

是否知道你不能在Kotlin中同步内联函数?我找不到任何关于此的文件.

想象一下,你有一个同步方法的类;

/**
 * Allows modifying the value in a synchronized way so that the get() and set() are atomic.
 *
 * Note: anything synchronized cannot be `inline`.
 */
@Synchronized fun safeSet(calculateNewValue: (T) -> T) {
    set(calculateNewValue(get()))
}
Run Code Online (Sandbox Code Playgroud)

当这个功能是inlined这个测试失败时,它不inlined通过.

@Test
fun `safeSet - is synchronized`() {
    val insideSet = AtomicInteger()
    val threadsRun = CountDownLatch(2)
    val t1 = Thread({
        threadsRun.countDown()
        sut.safeSet { currentValue: Int ->
            insideSet.incrementAndGet()
            try {
                Thread.sleep(100000)
            } catch (interrupted: InterruptedException) {
                BoseLog.debug(interrupted)
            }
            currentValue + 1
        }
    })
    t1.start()

    val t2 = Thread({
        threadsRun.countDown()
        sut.safeSet { currentValue: Int ->
            insideSet.incrementAndGet()
            try {
                Thread.sleep(100000)
            } catch (interrupted: InterruptedException) {
                BoseLog.debug(interrupted)
            }
            currentValue + 2
        }
    })
    t2.start()

    threadsRun.await()
    Thread.sleep(100)
    assertEquals(1, insideSet.get())
    t1.interrupt()
    t2.interrupt()
    Thread.sleep(100)
    assertEquals(2, insideSet.get())
}
Run Code Online (Sandbox Code Playgroud)

yol*_*ole 5

@Synchronized注解告诉编译器生成ACC_SYNCHRONIZED的方法标记.内联函数不会编译为方法,因此注释确实被忽略.

Kotlin 有一个未解决的问题,可以更好地处理这种情况.