test(concurrency): improve deadlock detection in BankAccount transfer stress test
This commit is contained in:
@@ -3,11 +3,10 @@ package banking;
|
|||||||
import dev.banking.model.BankAccount;
|
import dev.banking.model.BankAccount;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
import java.time.Duration;
|
|
||||||
|
|
||||||
public class BankAccountTransferDeadlockTest {
|
public class BankAccountTransferDeadlockTest {
|
||||||
|
|
||||||
@@ -19,17 +18,52 @@ public class BankAccountTransferDeadlockTest {
|
|||||||
BankAccount a = new BankAccount(1, 1_000_000);
|
BankAccount a = new BankAccount(1, 1_000_000);
|
||||||
BankAccount b = new BankAccount(2, 1_000_000);
|
BankAccount b = new BankAccount(2, 1_000_000);
|
||||||
|
|
||||||
|
int taskCount = 50_000;
|
||||||
|
|
||||||
ExecutorService executor = Executors.newFixedThreadPool(50);
|
ExecutorService executor = Executors.newFixedThreadPool(50);
|
||||||
|
|
||||||
for (int i = 0; i < 50_000; i++) {
|
CountDownLatch startGun = new CountDownLatch(1);
|
||||||
|
CountDownLatch finishLine = new CountDownLatch(taskCount * 2);
|
||||||
|
|
||||||
executor.submit(() -> a.transfer(b, 1));
|
for (int i = 0; i < taskCount; i++) {
|
||||||
executor.submit(() -> b.transfer(a, 1));
|
|
||||||
|
executor.submit(() -> {
|
||||||
|
try {
|
||||||
|
startGun.await();
|
||||||
|
a.transfer(b, 1);
|
||||||
|
} catch (InterruptedException ignored) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
} finally {
|
||||||
|
finishLine.countDown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
executor.submit(() -> {
|
||||||
|
try {
|
||||||
|
startGun.await();
|
||||||
|
b.transfer(a, 1);
|
||||||
|
} catch (InterruptedException ignored) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
} finally {
|
||||||
|
finishLine.countDown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
startGun.countDown();
|
||||||
|
|
||||||
|
boolean completed;
|
||||||
|
|
||||||
|
try {
|
||||||
|
completed = finishLine.await(5, TimeUnit.SECONDS);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
executor.shutdown();
|
executor.shutdown();
|
||||||
|
|
||||||
executor.awaitTermination(5, TimeUnit.SECONDS);
|
assertTrue(completed, "Deadlock detected: tasks did not complete in time");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user