简体   繁体   English

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

[英]Risks for locks in try-with-resources blocks in Java 8

If I do 如果我做

try(Lock lock = lockProvider.lock()) {
    // some code that doesn't use variable lock
}

Is there a risk that the compiler or the JITer to remove the lock creation because it sees it as unused inside the block? 编译器或JITer是否会删除锁定创建,因为它在块内未使用它,因此存在风险吗?


Later Edit: 以后编辑:

A bit of context. 有点背景。 I'm coming from a .NET Background where, in C#, it is allowed to do stuff such as: 我来自.NET背景,在C#中,它允许执行以下操作:

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

in fact it can even be shortened to 实际上,它甚至可以缩短为

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

The static compiler and the JIT compiler will keep the BeginTransaction call and at runtime it will always happen. 静态编译器和JIT编译器将保留BeginTransaction调用,并且在运行时将始终发生。

However in Java there seems to be a lot of issues and negativity around using try-with-resources for other things that are resources. 但是,在Java中,将try-with-resources用于其他资源(资源)似乎存在很多问题和消极问题。

No, there is no risk of the lock being optimized away, at least assuming its lock() and close() methods are not actually no-ops, but perform synchronization actions. 不,至少没有假设lock()没有被优化的风险,至少假设其lock()close()方法实际上不是空操作,而是执行同步操作。

The "negativity" you cite isn't about correctness, but just about using the tool the way it was intended, and how other tools, like static analyzers, can give you misleading guidance when you use AutoCloseable contrary to that intent. 您引用的“否定性”与正确性无关,而是与按预期方式使用该工具有关,以及当您使用AutoCloseable违反此意图时,其他工具(如静态分析器)如何为您提供误导性的指导。

By the way, if you do this, I recommend calling your wrapper something other than Lock to avoid confusion with java.util.concurrent.Lock . 顺便说一句,如果执行此操作,建议您使用除Lock来调用包装程序,以避免与java.util.concurrent.Lock混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM