Skip to content

Instantly share code, notes, and snippets.

@vrcca
Created October 18, 2018 14:41
Show Gist options
  • Save vrcca/1911930cf4154aa7980338b5f593e145 to your computer and use it in GitHub Desktop.
Save vrcca/1911930cf4154aa7980338b5f593e145 to your computer and use it in GitHub Desktop.
Deadlock example in Java
public class DeadlockExample {
private static final int NUM_THREADS = 20;
private static final int NUM_ACCOUNTS = 5;
private static final int NUM_ITERATIONS = 1000000;
public static void main(String[] args) {
final Random rnd = new Random();
final Account[] accounts = loadAllAccounts();
class TransferThread extends Thread {
private int id;
TransferThread(int id) {
this.id = id;
}
@Override
public void run() {
for (int i = 0; i < NUM_ITERATIONS; i++) {
log("[STARTED] Iteration " + i);
// simulates dead lock
int fromAcct = rnd.nextInt(NUM_ACCOUNTS);
int toAcct = rnd.nextInt(NUM_ACCOUNTS);
log("[TRYING] Thread-" + id + " TRYING to acquire lock for Account-" + fromAcct);
synchronized (accounts[fromAcct]) {
log("[LOCKED] Thread-" + id + " ACQUIRED lock for Account-" + fromAcct);
log("[TRYING] Thread-" + id + " TRYING to acquire lock for Account-" + toAcct);
synchronized (accounts[toAcct]) {
log("[LOCKED] Thread-" + id + " ACQUIRED lock for Account-" + toAcct);
// DO SOMETHING WITH ACCOUNTS
log("[TRANSFERED] Thread-" + id + " from Account-" + fromAcct + " to Account-" + toAcct);
log("[RELEASED] Thread-" + id + " RELEASED lock for Account-" + toAcct);
}
log("[RELEASED] Thread-" + id + " RELEASED lock for Account-" + fromAcct);
}
log("[ENDED] Iteration " + i);
}
}
private void log(String text) {
System.out.println(text);
}
}
// starts all threads
for (int i = 0; i < NUM_THREADS; i++) {
new TransferThread(i).start();
}
}
private static Account[] loadAllAccounts() {
return IntStream
.range(0, NUM_ACCOUNTS)
.mapToObj(Account::new)
.toArray(Account[]::new);
}
static class Account {
private int id;
Account(int id) {
this.id = id;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment