Compare commits

..

1 Commits
master ... dev

Author SHA1 Message Date
notme 3a7a83c7ec Dealock code added. 1 year ago
  1. 65
      src/test/java/org/chulk/sanxbox/TestConcurrency.java

65
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--;
}
}
}
}

Loading…
Cancel
Save