test(concurrency): improve deadlock detection in BankAccount transfer stress test

This commit is contained in:
2026-06-05 22:08:16 +03:30
parent 74963fbf29
commit 5f7cc2f255
@@ -3,11 +3,10 @@ package banking;
import dev.banking.model.BankAccount;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.concurrent.*;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.*;
public class BankAccountTransferDeadlockTest {
@@ -19,17 +18,52 @@ public class BankAccountTransferDeadlockTest {
BankAccount a = new BankAccount(1, 1_000_000);
BankAccount b = new BankAccount(2, 1_000_000);
int taskCount = 50_000;
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));
executor.submit(() -> b.transfer(a, 1));
for (int i = 0; i < taskCount; i++) {
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.awaitTermination(5, TimeUnit.SECONDS);
assertTrue(completed, "Deadlock detected: tasks did not complete in time");
});
}
}