Skip to content

Instantly share code, notes, and snippets.

@RomanVlasenko
Last active December 17, 2015 12:39
Show Gist options
  • Save RomanVlasenko/5611529 to your computer and use it in GitHub Desktop.
Save RomanVlasenko/5611529 to your computer and use it in GitHub Desktop.
Deadlock example
public class Operations {
public static void main(String[] args) {
final Account a = new Account(1000);
final Account b = new Account(2000);
new Thread(new Runnable() {
@Override
public void run() {
transfer(a, b, 500);
}
}).start();
transfer(b, a, 300);
}
private static void transfer(final Account sourceAccount, final Account destAccount, final int amount) {
System.out.println("Trying to lock source account...");
synchronized(sourceAccount) {
System.out.println("Source account locked.");
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("Trying to lock destination account...");
synchronized(destAccount) {
System.out.println("Destination account locked.");
if(sourceAccount.getBalance() < amount) throw new InsufficientFundsException();
sourceAccount.withdraw(amount);
destAccount.deposit(amount);
System.out.println("Transfer complete!");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment