To avoid multiple threads using a method at the same time, we can declare the method using synchronized keyword of Java like below:
1 2 3 4 5 6 7 8 |
package com.huongdanjava.lombok; public class Example { public synchronized int calculate(int a, int b) { return a + b; } } |
Project Lombok also provides a safer way to do this by using @Synchronized annotation.
1 2 3 4 5 6 7 8 9 10 11 |
package com.huongdanjava.lombok; import lombok.Synchronized; public class Example { @Synchronized public int calculate(int a, int b) { return a + b; } } |
With this annotation, Lombok will generate a private field named $lock for nonstatic method and a private field named $LOCK for static method. This will be safer way because it will allow use lock on an instance field rather than on this.
If you check the Example.class file in /target/classes/com/huongdanjava/lombok, you will see the content as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.huongdanjava.lombok; public class Example { private final Object $lock = new Object[0]; public Example() { } public int calculate(int a, int b) { Object var3 = this.$lock; synchronized(this.$lock) { return a + b; } } } |