Last active
December 17, 2015 12:39
-
-
Save RomanVlasenko/5611529 to your computer and use it in GitHub Desktop.
Deadlock example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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