diff --git a/src/test/java/org/chulk/sanxbox/TestConcurrency.java b/src/test/java/org/chulk/sanxbox/TestConcurrency.java index ee3ff1f..af68b80 100644 --- a/src/test/java/org/chulk/sanxbox/TestConcurrency.java +++ b/src/test/java/org/chulk/sanxbox/TestConcurrency.java @@ -1,5 +1,70 @@ package org.chulk.sanxbox; +import org.junit.jupiter.api.Test; + public class TestConcurrency { + private int counter = 0; + private final Object lock1 = new Object(); + private final Object lock2 = new Object(); + + @Test + public void testDeadlock() throws InterruptedException { + Runnable incRun = () -> { + try { + for (int i = 0; i < 100; i++) { + incrementCounter(); + System.out.println("Incrementing " + i); + } + } catch (InterruptedException ie) { + } + }; + + Runnable decRun = () -> { + try { + for (int i = 0; i < 100; i++) { + decrementCounter(); + System.out.println("Decrementing " + i); + } + } catch (InterruptedException ie) { + } + }; + + Thread thread1 = new Thread(incRun); + Thread thread2 = new Thread(decRun); + + thread1.start(); + // sleep to make sure thread 1 gets a chance to acquire lock1 + Thread.sleep(100); + thread2.start(); + + thread1.join(); + thread2.join(); + + System.out.println("Done : " + counter); + + } + + void incrementCounter() throws InterruptedException { + synchronized (lock1) { + System.out.println("Acquired lock1"); + Thread.sleep(100); + + synchronized (lock2) { + counter++; + } + } + } + + void decrementCounter() throws InterruptedException { + synchronized (lock2) { + System.out.println("Acquired lock2"); + + Thread.sleep(100); + synchronized (lock1) { + counter--; + } + } + } + }