1. Overview

Project Lombok is a Java library that provides various annotations we can use to generate standard methods and functionalities, reducing the boilerplate code. For instance, we can use Lombok to generate getters and setters, constructors, or even introduce design patterns in our code, such as the Builder pattern.

In this tutorial, we’ll learn how to use the @Locked annotation introduced in Lombok version 1.18.32.

2. Why @Locked Annotation?

First, let’s understand the need for the @Locked annotation.

Java 21 introduced virtual threads to ease concurrent applications’ implementation, maintenance, and debugging. What differentiates them from the standard threads is that they’re managed by the JVM instead of the operating system. Thus, their allocation doesn’t require a system call, nor do they depend on the operating system’s context switch.

However, we should be aware of potential performance problems virtual threads can yield. For instance, when the blocking operation is executed inside the synchronized block or a method, it still blocks the operating system’s thread. This situation is known as pinning. On the other hand, if the blocking operation is outside the synchronized block or a method, it wouldn’t cause any problems.

Furthermore, pinning can negatively affect the performance of our application, especially if the blocking operation is frequently called and long-lived. Notably, infrequent and short-lived blocking operations wouldn’t cause such problems.

One way to fix the pinning issue is to replace synchronized with the ReentrantLock. This is where the new Lombok annotation comes into play.

3. Understanding @Locked Annotation

Simply put, the @Locked annotation is created as a variant of the ReentrantLock. It was primarily designed to provide better support for virtual threads.

In addition, we can use this annotation only on static or instance methods. It wraps the entire code provided in a method into a block that acquires a lock. Moreover, we can specify the field of the ReentrantLock type we want to use for locking. As a result, Lombok performs a lock on that specific field. After the method finishes with execution, it unlocks.

Now, let’s see the @Locked annotation in action.

4. Dependency Setup

Let’s add the lombok dependency in our pom.xml:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.34</version>
    <scope>provided</scope>
</dependency>

It’s important to note we need version 1.18.32 or higher to use this annotation.

5. Usage

Let’s create the Counter class with the increment() and get() methods:

public class Counter {
    private int counter = 0;
    private ReentrantLock lock = new ReentrantLock();
    
    public void increment() {
        lock.lock();
        try {
            counter++;
        } finally {
            lock.unlock();
        }
    }

    public int get() {
        lock.lock();
        try {
            return counter;
        } finally {
            lock.unlock();
        }
    }
}

Since counter++ isn’t an atomic operation, we needed to include locking to ensure the atomic update of the shared object is visible by other threads in a multithreaded environment. Otherwise, we’ll get incorrect results.

Here, we used the ReentrantLock to lock the increment() and get() methods, ensuring only one thread can call the method at a time.

Let’s replace the lock in the increment() and get() methods and use the @Locked annotation instead:

@Locked
public void increment() {
    counter++;
}

@Locked
public int get() {
    return counter;
}

We reduced the number of lines to just one per method. Now, let’s understand what happens under the hood. Lombok creates a new field of ReentrantLock type named $LOCK or $lock, depending on whether we’re using locking on a static or instance method.

Then, it wraps the code provided in the method into a block that acquires ReentrantLock. Finally, when we exit the method, it releases the lock.

Furthermore, multiple methods annotated with the @Locked annotation will share the same lock. If we need different locks, we can create a ReentrantLock instance variable and pass its name as an argument to the @Locked annotation.

Let’s test the methods to ensure they work properly:

@Test
void givenCounter_whenIncrementCalledMultipleTimes_thenReturnCorrectResult() throws InterruptedException {
    Counter counter = new Counter();

    Thread.Builder builder = Thread.ofVirtual().name("worker-", 0);
    Runnable task = counter::increment;

    Thread t1 = builder.start(task);
    t1.join();

    Thread t2 = builder.start(task);
    t2.join();

    assertEquals(2, counter.get());
}

5.1. @Locked.Read and @Locked.Write Annotations

We can use the @Locked.Read and @Locked.Write annotations instead of ReentrantReadWriteLock.

As the name suggests, methods decorated with the @Locked.Read lock on the read lock, while the methods annotated with the @Locked.Write lock on the write lock.

Let’s modify the code provided in the increment() and get() method and use the @Locked.Write and @Locked.Read annotations:

@Locked.Write
public void increment() {
    counter++;
}

@Locked.Read
public int get() {
    return counter;
}

As a reminder, having separate locks for read and write operations can improve performance, especially when the operation is heavy.

Notably, the name of the ReentrantReadWriteLock field Lombok creates is the same as the one generated for the @Locked annotation. Thus, we’d need to specify a custom name for one of the locks if we want to use both annotations in the same class.

6. Difference Between @Locked and @Synchronized

Besides the @Locked annotation, Lombok provides a similar @Synchronized annotation. Both annotations serve the purpose of ensuring thread safety. Let’s find out the differences between them.

While the @Locked annotation is a substitution for the ReentrantLock, the @Synchonized annotation replaces the synchronized modifier. Just like the keyword, we can use it only on static or instance methods. However, while synchronized locks on this, the annotation locks on the specific field created by Lombok.

Additionally, the @Locked annotation is recommended when using virtual threads, while using @Synchronized in the same situation can cause performance issues.

7. Conclusion

In this article, we learned how to use Lombok’s @Locked annotation.

To sum up, Lombok introduced the annotation for better support of virtual threads. It represents a substitution for the ReentrantLock object. Alternatively, we saw how to use the @Lock.Read and @Lock.Write annotations to specify read and write locks instead of using the general one. Finally, we highlighted several differences between the @Locked and the @Synchronized annotations.

As always, the source code for the article is available over on GitHub.