Kostiggig

Nested monitor lock out

Apr 30th, 2023
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. package multithreading.nested_monitor_lockout;
  2.  
  3. public class SomeObject {
  4.  
  5.     private final Object monitor = new Object();
  6.  
  7.     public void foo1() throws InterruptedException {
  8.         System.out.println(Thread.currentThread().getName() + " enters foo1()");
  9.         synchronized(this) {
  10.             System.out.println(Thread.currentThread().getName() + " locks this");
  11.             synchronized (monitor) {
  12.                 System.out.println(Thread.currentThread().getName() + " locks monitor");
  13.                 System.out.println(Thread.currentThread().getName() + " calls monitor.wait() and releases monitor");
  14.                 monitor.wait(); // after calling curr thread releases lock on a monitor object
  15.             }
  16.         }
  17.     }
  18.  
  19.     public void foo2() {
  20.         System.out.println(Thread.currentThread().getName() + " enters foo2()");
  21.         synchronized (this) {
  22.             System.out.println(Thread.currentThread().getName() + " locks this");
  23.             synchronized (monitor) {
  24.                 System.out.println(Thread.currentThread().getName() + " locks monitor");
  25.                 monitor.notify();
  26.                 System.out.println(Thread.currentThread().getName() + " calls monitor.notify() and releases monitor");
  27.             }
  28.         }
  29.     }
  30. }
  31.  
  32.  
  33. public class Client {
  34.  
  35.     public static void main(String[] args) throws InterruptedException {
  36.         SomeObject someObject = new SomeObject();
  37.         new Thread(() -> {
  38.             try {
  39.                 someObject.foo1();
  40.             } catch (InterruptedException e) {
  41.                 throw new RuntimeException(e);
  42.             }
  43.         }, "ThreadA").start();
  44.  
  45.         Thread.sleep(3000); // needed to run ThreadA earlier than ThreadB
  46.         new Thread(() -> someObject.foo2(), "ThreadB").start();
  47.     }
  48. }
Add Comment
Please, Sign In to add comment