/** * Show an example of deadlock. * * On Linux, set LD_ASSUME_KERNEL to 2.4.1: * csh: setenv LD_ASSUME_KERNEL 2.4.1 * bash: export LD_ASSUME_KERNEL=2.4.1 * * Run with "java Account" * On deadlock, use ^Z to suspend. * Use "ps" to find process ids of Java threads. * Invoke "jstack pid" on any of the pids listed * * @author Godmar Back gback@cs.vt.edu, Feb 2006 */ public class Account { private int amount; private String name; Account(String name, int amount) { this.name = name; this.amount = amount; } void transferTo(Account that, int amount) { synchronized (this) { // lock this account synchronized (that) { // lock other account System.out.println("Transfering $" + amount + " from " + this.name + " to " + that.name); this.amount -= amount; that.amount += amount; } } } public static void main(String []av) throws Exception { final Account acc1 = new Account("acc1", 10000); final Account acc2 = new Account("acc2", 10000); Thread t = new Thread() { public void run() { for (int i = 0; i < 100000; i++) acc1.transferTo(acc2, 20); } }; t.start(); for (int i = 0; i < 100000; i++) acc2.transferTo(acc1, 20); t.join(); } }