From 3a7a83c7ec46740f76bb06515d38160a3d165164 Mon Sep 17 00:00:00 2001 From: notme Date: Tue, 4 Jul 2023 23:15:57 +0200 Subject: [PATCH] Dealock code added. --- .../org/chulk/sanxbox/TestConcurrency.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) 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--; + } + } + } + }