@Locked
Pop it and lock it! ReentrantLock, now with less hassle.
@Locked was introduced in lombok v1.18.32.
Overview
@Locked wraps all code in a method into a block that acquires a java.util.concurrent.locks.ReentrantLock first, and unlocks it when exiting the method. It is a lot like @Synchronized.
You can optionally name a field, which must be a ReentrantLock; in that case, lombok locks on that field. Otherwise, the annotation defaults to a field named $LOCK (on static methods) / $lock (on instance methods), which lombok will generate if the field does not exist yet.
Additionally, there are the @Locked.Read and @Locked.Write annotations. These use a java.util.concurrent.locks.ReadWriteLock (specifically, ReentrantReadWriteLock). Methods annotated with @Locked.Write will lock on the write lock and methods annotated with @Locked.Read will lock on the read lock. When required, a java.util.concurrent.locks.ReentrantReadWriteLock is generated.
When using Virtual threads (introduced in Java 20), these locks are recommended compared to what @Synchronized does.
With Lombok
import lombok.Locked;
|
Vanilla Java
public class LockedExample {
|
Supported configuration keys:
-
lombok.locked.flagUsage= [warning|error] (default: not set) -
Lombok will flag any usage of
@Lockedas a warning or error if configured.
Small print
Because @Locked.Read and @Locked.Write use a different type of lock than @Locked, these annotations cannot be used on the same lock object without explicitly specifying the name of the field containing the lock object.
The name of the default field of the @Locked, @Locked.Read, and @Locked.Write annotations is the same, so it is not possible to mix the basic @Locked annotation with the other two using the default name.