일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- 소프트웨어공학
- NIO
- 자바
- Java
- 자바네트워크
- 시스템
- write by GPT-4
- 인프라
- 리눅스
- spring data jpa
- 코틀린
- write by chatGPT
- Database
- kotlin
- 역학
- JVM
- 파이썬
- android
- chatGPT's answer
- jpa
- 유닉스
- python
- 자바암호
- 데이터베이스
- spring integration
- oracle
- flet
- 웹 크롤링
- GPT-4's answer
- 고전역학
- Today
- Total
Akashic Records
Lombok features - @Synchronized 본문
synchronized done right: Don't expose your locks.
Overview
@Synchronized is a safer variant of the synchronized method modifier. Like synchronized, the annotation can be used on static and instance methods only. It operates similarly to the synchronized keyword, but it locks on different objects. The keyword locks on this, but the annotation locks on a field named $lock, which is private.
If the field does not exist, it is created for you. If you annotate a static method, the annotation locks on a static field named $LOCK instead.
If you want, you can create these locks yourself. The $lock and $LOCK fields will of course not be generated if you already created them yourself. You can also choose to lock on another field, by specifying it as parameter to the @Synchronized annotation. In this usage variant, the fields will not be created automatically, and you must explicitly create them yourself, or an error will be emitted.
Locking on this or your own class object can have unfortunate side-effects, as other code not under your control can lock on these objects as well, which can cause race conditions and other nasty threading-related bugs.
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"); } } |
Vanilla Java
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"); } } } |
Supported configuration keys:
lombok.synchronized.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @Synchronized as a warning or error if configured.
'Library' 카테고리의 다른 글
Docker Compose 설치 (0) | 2021.01.07 |
---|---|
Lombok features - @With (0) | 2020.12.21 |
Lombok features - @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor (0) | 2020.12.21 |
Lombok features - @EqualsAndHashCode (0) | 2020.12.21 |
Lombok features - @ToString (0) | 2020.12.21 |