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?
Later Edit:
A bit of context. I'm coming from a .NET Background where, in C#, it is allowed to do stuff such as:
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.
However in Java there seems to be a lot of issues and negativity around using try-with-resources for other things that are 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.
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.
By the way, if you do this, I recommend calling your wrapper something other than Lock
to avoid confusion with java.util.concurrent.Lock
.