Java 8中try-with-resources块中的锁的风险

And*_*nea 2 java optimization jit java-8 javacompiler

如果我做

try(Lock lock = lockProvider.lock()) {
    // some code that doesn't use variable lock
}
Run Code Online (Sandbox Code Playgroud)

编译器或JITer是否存在删除锁创建的风险,因为它在块中看到它未使用?


后来编辑:

一点背景.我来自.NET背景,在C#中,它允许执行以下操作:

using(Transaction tx = BeginTransaction())
{
    // code that does things without touching the tx variable, such as SQL connections and stuff
}
Run Code Online (Sandbox Code Playgroud)

事实上它甚至可以缩短为

using(BeginTransaction())
{
    // code that does things without touching the tx variable, such as SQL connections and stuff
}
Run Code Online (Sandbox Code Playgroud)

静态编译器和JIT编译器将保持BeginTransaction调用,并且在运行时它将始终发生.

然而,在Java似乎是一个很大的问题和消极周围使用try-与资源用于其他的东西,是资源.

eri*_*son 6

不,没有锁被优化的风险,至少假设它lock()close()方法实际上不是无操作,而是执行同步操作.

你引用的"否定性"不是关于正确性,而是关于按照预期的方式使用工具,以及当你使用AutoCloseable违背意图时,静态分析器等其他工具如何能够给你误导性的指导.

顺便说一下,如果你这样做,我建议你打电话给你的包装器,Lock以避免混淆java.util.concurrent.Lock.