Skip to content
Java project #24Advanced

Concurrent Bank Simulator

Hammer two thread-safe bank implementations with the same random workload on many threads and verify that money is conserved, no balance goes negative and the results match a sequential replay.

Estimated time
~8 hours to build
Files
5 files · 343 lines
Technologies
Java 21, synchronized, ReentrantLock, ExecutorService, CountDownLatch, AtomicLong

Introduction

Concurrency bugs hide in timing. This project avoids that trap twice over: it implements transfers with two deadlock-free locking strategies, and it designs its experiment so that the correct final state is known in advance and can be checked exactly, however the threads interleave.

Problem statement

Read the number of accounts, threads, transfers per thread and a random seed. Generate a reproducible list of transfers for each thread. Run all threads simultaneously (released together by a latch) against a bank using synchronized blocks with global lock ordering, and then against a bank using ReentrantLock with timed tryLock and back-off. For each, verify that the total money is unchanged, no balance is negative, the final balances equal a single-threaded replay, and both strategies agree. Opening balances are chosen so that no transfer can fail, which makes the expected result independent of timing.

Objectives

  • Prevent deadlock with lock ordering and with tryLock back-off
  • Design concurrent tests whose correct answer is deterministic
  • Coordinate threads with ExecutorService, CountDownLatch and Futures
  • Count events safely with AtomicLong

Features

  • Two interchangeable thread-safe strategies (abstract class)
  • Reproducible, seeded workloads
  • Invariant checks: conservation, non-negativity, sequential equivalence
  • Identical output on every run

Concepts demonstrated

  • Race conditions
  • Deadlock avoidance
  • Lock ordering
  • Back-off
  • Deterministic testing of concurrent code

System architecture

Bank is abstract with two nested implementations. OrderedLocks gives every account its own monitor and always locks the lower index first, so a cycle of waiting threads can't form. TryLocks locks in the caller's order (which would deadlock with plain lock()), but if the second lock isn't free within 50 µs it releases the first, yields and retries. Main generates the transfers from the seed, computes the expected balances sequentially, runs each bank on a fixed pool with a start latch, and compares the results. Each account starts with (total transfers × maximum amount), so a transfer can never be rejected.

Folder structure

TextProject tree
concurrent-bank-simulator/
├── README.md
├── src/Bank.java
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Bank.java

111 lines
Javasrc/Bank.java
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
/** A bank whose accounts can be transferred between concurrently, using one of two strategies. */
public abstract class Bank {
protected final long[] balances;
protected final AtomicLong succeeded = new AtomicLong(), rejected = new AtomicLong();
protected Bank(int accounts, long opening) {
balances = new long[accounts];
java.util.Arrays.fill(balances, opening);
}
/** Moves money if the source has enough; must be safe to call from many threads. */
public abstract boolean transfer(int from, int to, long amount) throws InterruptedException;
public abstract long balance(int account);
public abstract String strategy();
public long total() {
long t = 0;
for (int i = 0; i < balances.length; i++) t += balance(i);
return t;
}
public long succeeded() { return succeeded.get(); }
public long rejected() { return rejected.get(); }
public int size() { return balances.length; }
/** Strategy 1: one intrinsic lock object per account, always acquired lowest index first. */
public static final class OrderedLocks extends Bank {
private final Object[] locks;
public OrderedLocks(int accounts, long opening) {
super(accounts, opening);
locks = new Object[accounts];
for (int i = 0; i < accounts; i++) locks[i] = new Object();
}
@Override public boolean transfer(int from, int to, long amount) {
if (from == to || amount <= 0) throw new IllegalArgumentException("invalid transfer");
int first = Math.min(from, to), second = Math.max(from, to); // global lock order: no deadlock possible
synchronized (locks[first]) {
synchronized (locks[second]) {
if (balances[from] < amount) { rejected.incrementAndGet(); return false; }
balances[from] -= amount;
balances[to] += amount;
succeeded.incrementAndGet();
return true;
}
}
}
@Override public long balance(int a) { synchronized (locks[a]) { return balances[a]; } }
@Override public String strategy() { return "synchronized with lock ordering"; }
}
/**
* Strategy 2: ReentrantLock with a timed tryLock. Locks are taken in the caller's order, which
* would deadlock with plain lock() calls; instead, if the second lock isn't free within 50 µs
* the thread releases the first one, yields and retries, so no two threads wait forever.
*/
public static final class TryLocks extends Bank {
private final ReentrantLock[] locks;
private final AtomicLong retries = new AtomicLong();
public TryLocks(int accounts, long opening) {
super(accounts, opening);
locks = new ReentrantLock[accounts];
for (int i = 0; i < accounts; i++) locks[i] = new ReentrantLock();
}
@Override public boolean transfer(int from, int to, long amount) throws InterruptedException {
if (from == to || amount <= 0) throw new IllegalArgumentException("invalid transfer");
while (true) {
if (Thread.interrupted()) throw new InterruptedException();
locks[from].lockInterruptibly(); // wait for the first lock...
try {
if (locks[to].tryLock(50, TimeUnit.MICROSECONDS)) { // ...but give up on the second quickly
try {
if (balances[from] < amount) { rejected.incrementAndGet(); return false; }
balances[from] -= amount;
balances[to] += amount;
succeeded.incrementAndGet();
return true;
} finally {
locks[to].unlock();
}
}
} finally {
locks[from].unlock();
}
retries.incrementAndGet();
Thread.yield(); // release everything and let other threads progress, then retry
}
}
@Override public long balance(int a) {
locks[a].lock();
try { return balances[a]; } finally { locks[a].unlock(); }
}
public long retries() { return retries.get(); }
@Override public String strategy() { return "ReentrantLock.tryLock with back-off"; }
}
}

What each file does

src/Bank.java
The abstract bank and its two locking strategies.
src/Main.java
Workload generation, the concurrent run with a start latch, and the invariant checks.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
6 accounts x Rs 800,000, 8 threads x 2000 transfers (seed 2026)
Strategy: synchronized with lock ordering
transfers succeeded 16,000, rejected 0
total money 4,800,000 (expected 4,800,000): conserved
no negative balances: true
balances match a sequential replay: true
Strategy: ReentrantLock.tryLock with back-off
transfers succeeded 16,000, rejected 0
total money 4,800,000 (expected 4,800,000): conserved
no negative balances: true
balances match a sequential replay: true
same final balances as the first strategy: true
Final balances:
account 0: 800,911 (+911)
account 1: 797,249 (-2,751)
account 2: 799,903 (-97)
account 3: 801,834 (+1,834)
account 4: 801,320 (+1,320)
account 5: 798,783 (-1,217)
Input
6 8 2000 2026

Testing

  • Run with tests/sample-input.txt (6 accounts, 8 threads, 2,000 transfers each, seed 2026) and compare with tests/expected-output.txt.
  • Both strategies complete all 16,000 transfers, conserve the ₹4,800,000 total and match the sequential replay.
  • Run the test several times: the output never changes, although the threads interleave differently each time.
  • Pass --verbose to see the number of tryLock retries, which does vary between runs.

Common errors

The program hangs

Two threads are each holding one lock and waiting for the other: order the locks globally or use tryLock with back-off.

The total changes between runs

Some update happens outside the locks; every read and write of shared balances must hold the account's lock.

Possible improvements

  • Add an unsafe implementation to demonstrate lost updates
  • Measure throughput of each strategy with JMH
  • Use StampedLock for balance reads

Additional challenges

  1. 1Allow transfers to fail for insufficient funds and verify conservation still holds.
  2. 2Add a third strategy using a single global lock and compare.
  3. 3Detect deadlocks with ThreadMXBean when ordering is removed.

Built and tested it yourself? Mark it to update your dashboard.