As you probably know, to avoid multiple threads using a method at the same time, we can declare the method using the synchronized keyword in Java programs.
In this example, we will see how to use @Synchronized annotation to make Java methods synchronized.
In this example, we will see how to use @Synchronized annotation to make Java methods synchronized.
Project Lombok Maven
- Create a simple maven project using - How to Create a Simple Maven Project in Eclipse article.
- Add the below dependency in your maven project pom.xml file:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
Adding the Lombok Plugin in IDE (Eclipse)
Follow below steps to install Lombok in eclipse for Windows:
- Downloaded jar from https://projectlombok.org/download or use the jar which is downloaded from your maven build.
- Execute command in terminal: java -jar lombok.jar
- This command will open window as shown in the picture below, install and quit the installer and restart eclipse.
With Lombok
import lombok.Synchronized;
public class SynchronizedExample {
private final Object readLock = new Object();
@Synchronized
public static void hello() {
System.out.println("world");
}
@Synchronized
public int answerToLife() {
return 42;
}
@Synchronized("readLock")
public void foo() {
System.out.println("bar");
}
}
Without Lombok
public class SynchronizedExample {
private static final Object $LOCK = new Object[0];
private final Object $lock = new Object[0];
private final Object readLock = new Object();
public static void hello() {
synchronized($LOCK) {
System.out.println("world");
}
}
public int answerToLife() {
synchronized($lock) {
return 42;
}
}
public void foo() {
synchronized(readLock) {
System.out.println("bar");
}
}
}
Reference
GitHub Repository
You can view the source code of this article on my GitHub repository at https://github.com/RameshMF/project-lombok-tutorial
Comments
Post a Comment
Leave Comment