001package edu.pdx.cs410J.net;
002
003/**
004 * Transfers money between two <code>BankAccount</code>s.
005 * Has the potential to deadlock.
006 */
007public class Transfer implements Runnable {
008  private BankAccount src;
009  private BankAccount dest;
010  private int amount;
011
012  /**
013   * Sets up a transfer between two accounts.
014   */
015  public Transfer(BankAccount src, 
016                  BankAccount dest, int amount) {
017    this.src = src;
018    this.dest = dest;
019    this.amount = amount;
020  }
021
022  /**
023   * Performs the transfer.
024   */
025  public void run() {
026    System.out.println("Transferring " + this.amount);
027
028    // Have to obtain locks on both accounts
029    synchronized(this.src) {
030      int srcBalance = src.getBalance();
031
032      synchronized(this.dest) {
033        int destBalance = dest.getBalance();
034
035        src.setBalance(srcBalance - this.amount);
036        dest.setBalance(destBalance + this.amount);
037      }
038    }
039  }
040
041  /**
042   * Creates and performs a <code>Transfer</code>
043   */
044  public static void main(String[] args) {
045    BankAccount acc1 = new BankAccount();
046    acc1.setBalance(1000);
047    BankAccount acc2 = new BankAccount();
048    acc2.setBalance(500);
049
050    (new Thread(new Transfer(acc1, acc2, 300))).start();
051    (new Thread(new Transfer(acc2, acc1, 100))).start();
052  }
053}