SoFunction
Updated on 2025-03-05

Java uses try-with-resources to achieve automatic unlocking

background

Use Redission distributed locks in the project, and each use is required to display the unlock. Very troublesome, Java providestry-with-resourcesSyntax sugar, which can not only be used to automatically close streaming resources, but also to achieve automatic unlocking.

This article will introduce how to use ittry-with-resourcesImplement automatic release of locks and demonstrate its application through code examples.

What are try-with-resources?

try-with-resourcesis a syntax introduced in Java 7 that simplifies the process of closing resources. The traditional way is throughfinallyBlocks manually close resources, but this can cause code to be lengthy and error-prone. andtry-with-resourcesThe resource closure will be automatically managed, and the resource used must be implementedAutoCloseableinterface.

How to use locks with try-with-resources?

To usetry-with-resourcesAutomatically unlock, we can wrap the lock into one implementationAutoCloseableThe class of the interface. In this way,tryWhen the statement block ends, the lock will be automatically released. Below we will implement a simple example to show how to passtry-with-resourcesImplement automatic unlocking.

Sample code

public class VVRLock implements AutoCloseable {

    private RLock rLock;

    private RedissonClient redissonClient;

    public VVRLock(RedissonClient redissonClient) {
         = redissonClient;
    }


    @Override
    public void close() throws Exception {
        if (rLock != null && ()) {
            ();
            ("auto unlock key:{}", ());
        }
    }

    public boolean tryLock(String key) {
         = (key);
        return ();
    }
    
}

When using lock

    public void checkQuitGroupRecords() {
        try (VVRLock lock = new VVRLock(redissonClient)) {
            if (!(())) {
                return;
                // todo business process            }
            
        } catch (Exception e) {
            ("checkQuitGroupRecords ", e);
        }
    }

Code parsing

  • Initialization of locks: We useRedissionTo implement a reentrant locklock. It is a typical thread-safe lock that supports fairness and reentry.
  • AutoUnlock class: We created aVVRLockclass, it implementsAutoCloseableinterface. In the constructor, it acquires the lock immediately when the object is created, whileclose()The lock will be automatically released in the method.
  • try-with-resources: In the locking method, we passtry-with-resourcesStatements to manageVVRLockObject. When each thread executes, it will entertryblock and automatically acquire locks, whiletryWhen the block is executed,VVRLockThe object will be closed and the lock will be automatically released.

Why can try-with-resources be unlocked automatically?

try-with-resourcesThe key behind the syntax is that it requires resource objects to be implementedAutoCloseableinterface. By wrapping the lock in oneAutoCloseableIn the interface class, we can usetry-with-resourcesAutomatically release the resource (i.e., lock) when it is no longer needed. In fact, after jvm is compiled, the code will be restored totry-catch-finallymodel

advantage

  • Simplicity: passtry-with-resourcesWe don't need to explicitlyfinallyRelease the lock in the block, making the code more concise.
  • reliability: The release of locks no longer depends on whether the developer writes correctlyfinallyStatement blocks are automatically processed by Java's resource management mechanism, thereby reducing the risk of deadlocks.
  • Maintainability: Through the acquisition and release of encapsulation locks, we improve the maintainability of the code, making the logic of concurrent control clearer.

Things to note

  • Lock reentry problem: VVRLockis a reentrant lock, meaning that the same thread can acquire the lock multiple times without deadlocking. If you use non-reentrant locks, make sure that each thread can only be in onetry-with-resourcesGet locks in blocks.
  • Exception handling: existclose()In the method, we can add additional exception handling logic to ensure that no exceptions are ignored during lock release.

Summarize

By usingtry-with-resourcesandAutoCloseableWith interface, we can easily realize the automatic release of locks. This approach can not only improve the simplicity and maintainability of the code, but also avoid deadlocks or resource leakage problems caused by forgetting to release the lock. This pattern is very useful in multi-threaded programming, especially when dealing with shared resources, which can effectively ensure the security of resources and the accuracy of concurrent control.

The above is the detailed content of Java using try-with-resources to achieve automatic unlocking. For more information about Java try-with-resources automatic unlocking, please follow my other related articles!