synchronized 동작 방식을 읽고 문득 궁금점이 생겼다.
synchronized를 사용하면 monitor lock을 활용하는데 minitor는 instance당 1개만 있다는 것이다. 그래서 그럼 같은 instance 내에 2개의 synchronized block을 사용하면 lock을 각각 획득하지 못하나? 라는 궁금점이 들었다.
그래서 아래와 같은 테스트를 작성했다.
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) throws Exception {
Test test = new Test();
Thread thread = new Thread(() -> {
try {
test.test1();
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(LocalDateTime.now() + " : Thread 1 Done");
});
Thread thread2 = new Thread(() -> {
try {
test.test2();
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println(LocalDateTime.now() + " : Thread 2 Done");
});
thread.start();
thread2.start();
}
}
class Test {
public void test1() throws Exception {
Thread.sleep(5000);
}
public void test2() throws Exception {
Thread.sleep(5000);
}
}
> Task :Main.main()
2024-10-20T14:30:32.146232 : Thread 1 Done
Disconnected from the target VM, address: 'localhost:61712', transport: 'socket'
2024-10-20T14:30:37.131532 : Thread 2 Done
2024-10-20T14:31:02.123639 : Thread 1 Done
2024-10-20T14:31:02.123617 : Thread 2 Done
같은 instance 내에는 모니터가 1개라서 synchronized block을 여러개 쓴다고해도 lock을 각각 얻을 수 없다.