Java Reference
In-Depth Information
Example 16−2: RemoteBankServer.java (continued)
// Check if there is already an account under that name
if (accounts.get(name) != null)
throw new BankingException("Account already exists.");
// Otherwise, it doesn't exist, so create it.
Account acct = new Account(password);
// And register it
accounts.put(name, acct);
}
/**
* This internal method is not a remote method. Given a name and password
* it checks to see if an account with that name and password exists. If
* so, it returns the Account object. Otherwise, it throws an exception.
**/
Account verify(String name, String password) throws BankingException {
synchronized(accounts) {
Account acct = (Account)accounts.get(name);
if (acct == null) throw new BankingException("No such account");
if (!password.equals(acct.password))
throw new BankingException("Invalid password");
return acct;
}
}
/**
* Close the named account. This method is synchronized to make it
* thread safe, since it manipulates the accounts hashtable.
**/
public synchronized FunnyMoney closeAccount(String name, String password)
throws RemoteException, BankingException
{
Account acct;
acct = verify(name, password);
accounts.remove(name);
// Before changing the balance or transactions of any account, we first
// have to obtain a lock on that account to be thread safe.
synchronized (acct) {
int balance = acct.balance;
acct.balance = 0;
return new FunnyMoney(balance);
}
}
/** Deposit the specified FunnyMoney to the named account */
public void deposit(String name, String password, FunnyMoney money)
throws RemoteException, BankingException
{
Account acct = verify(name, password);
synchronized(acct) {
acct.balance += money.amount;
acct.transactions.add("Deposited " + money.amount +
" on " + new Date());
}
}
/** Withdraw the specified amount from the named account */
public FunnyMoney withdraw(String name, String password, int amount)
throws RemoteException, BankingException
Search WWH ::




Custom Search