如果我这样做
try(Lock lock = lockProvider.lock()) {
// some code that doesn't use variable lock
}
编译器或JITer是否存在删除锁创建的风险,因为它在块中看到它未使用?
稍后编辑:
一点背景。我来自.NET背景,在C#中,它允许执行诸如以下的操作:
using(Transaction tx = BeginTransaction())
{
// code that does things without touching the tx variable, such as SQL connections and stuff
}
实际上它甚至可以缩短为
using(BeginTransaction())
{
// code that does things without touching the tx variable, such as SQL connections and stuff
}
静态编译器和JIT编译器将保持BeginTransaction
调用,并且在运行时它将始终发生。
然而,在Java中,似乎存在许多问题,并且negativity围绕将资源尝试用于其他资源。
答案 0 :(得分:6)
不,没有优化锁的风险,至少假设其lock()
和close()
方法实际上不是无操作,而是执行同步操作。
您引用的"negativity"并不是关于正确性,而只是按照预期的方式使用该工具,以及当您使用{{{}时,其他工具(如静态分析器)如何为您提供误导性指导与此意图相反。
顺便说一句,如果您这样做,我建议您调用包装器而不是AutoCloseable
,以避免与Lock
混淆。