Question

In: Computer Science

Problem: Add a condition to the deposit method of the BankAccount class, restricting deposits to $100,000...

Problem:

Add a condition to the deposit method of the BankAccount class, restricting deposits to $100,000 (the insurance limit of the U.S. government). The method should block until sufficient money has been withdrawn by another thread. Test your program with a large number of deposit threads.

Bank account class: (THE ONE THAT NEEDS TO BE EDITED)

/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
private double balance;

/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
balance = 0;
}

/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
System.out.print("Depositing " + amount);
double newBalance = balance + amount;
System.out.println(", new balance is " + newBalance);
balance = newBalance;
}

/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
System.out.print("Withdrawing " + amount);
double newBalance = balance - amount;
System.out.println(", new balance is " + newBalance);
balance = newBalance;
}

/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
}

Included for test classes:

Bank Account threadrunner.java

/**
This program runs threads that deposit and withdraw
money from the same bank account.
*/
public class BankAccountThreadRunner
{
public static void main(String[] args)
{
BankAccount account = new BankAccount();
final double AMOUNT = 100;
final int REPETITIONS = 100;
final int THREADS = 100;

for (int i = 1; i <= THREADS; i++)
{
DepositRunnable d = new DepositRunnable(
account, AMOUNT, REPETITIONS);
WithdrawRunnable w = new WithdrawRunnable(
account, AMOUNT, REPETITIONS);

Thread dt = new Thread(d);
Thread wt = new Thread(w);

dt.start();
wt.start();
}
}
}

Withdraw runnable.java:

/**
A withdraw runnable makes periodic withdrawals from a bank account.
*/
public class WithdrawRunnable implements Runnable
{
private static final int DELAY = 1;
private BankAccount account;
private double amount;
private int count;

/**
Constructs a withdraw runnable.
@param anAccount the account from which to withdraw money
@param anAmount the amount to withdraw in each repetition
@param aCount the number of repetitions
*/
public WithdrawRunnable(BankAccount anAccount, double anAmount,
int aCount)
{
account = anAccount;
amount = anAmount;
count = aCount;
}

DepositRunnable.java

/**
A deposit runnable makes periodic deposits to a bank account.
*/
public class DepositRunnable implements Runnable
{
private static final int DELAY = 1;
private BankAccount account;
private double amount;
private int count;

/**
Constructs a deposit runnable.
@param anAccount the account into which to deposit money
@param anAmount the amount to deposit in each repetition
@param aCount the number of repetitions
*/
public DepositRunnable(BankAccount anAccount, double anAmount,
int aCount)
{
account = anAccount;
amount = anAmount;
count = aCount;
}

public void run()
{
try
{
for (int i = 1; i <= count; i++)
{
account.deposit(amount);
Thread.sleep(DELAY);
}
}
catch (InterruptedException exception) {}
}
}

Solutions

Expert Solution

Problem:

Add a condition to the deposit method of the BankAccount class, restricting deposits to $100,000 (the insurance limit of the U.S. government). The method should block until sufficient money has been withdrawn by another thread. Test your program with a large number of deposit threads.

Bank account class: (THE ONE THAT NEEDS TO BE EDITED)


Explanation:

Given question is of bank accounts

and thread program for withdraw and deposit functionality

Brief description of solution:

synchronized(this)

it is used to avoid exception Illegal Monitor State Exception as it is done if calling thread does not own the specified monitor means current execution so adding synchronization means till this thread is stopped no such same thread is called again like if deposit thread is on wait no such deposit thread is called

for wait, notify and notify all method, the calling thread must own therefore own the monitor.

concept of wait and notify

wait is used to allow to take a timeout specified by millisecond if not specified then it will be infinite until it is notified

whereas notify is to wake up thread waiting for a particular object

Solution code:

BankAccount./**

This program runs threads that deposit and withdraw

money from the same bank account.

*/

public class BankAccountThreadRunner

{

public static void main(String[] args)

{

BankAccount account = new BankAccount();

final double AMOUNT = 100;

final int REPETITIONS = 100;

final int THREADS = 100;

for (int i = 1; i <= THREADS; i++)

{

DepositRunnable d = new DepositRunnable(

account, AMOUNT, REPETITIONS);

WithdrawRunnable w = new WithdrawRunnable(

account, AMOUNT, REPETITIONS);

Thread dt = new Thread(d);

Thread wt = new Thread(w);

dt.start();

wt.start();

}

}

}

BankAccount.java {class}

//code is well commented for better understanding

/**
A bank account has a balance that can be changed by
deposits and withdrawals.
 */
public class BankAccount
{
        private double balance;

        /**
Constructs a bank account with a zero balance.
         */
        public BankAccount()
        {
                balance = 0;
        }

        /**
Deposits money into the bank account.
@param amount the amount to deposit
         * @throws InterruptedException 
         */
        public void deposit(double amount) throws InterruptedException
        {
                //to check for balance limitation and can not be more than given limit(100000)
                //so have to wait for other threads until they withdraw amount
                if(balance>=100000)
                {
                        synchronized (this)
                        {
                                wait();
                        }
                }
                else
                {
                        //no notifying thread so it wake up and does not wait
                        //if this was not there then deposit would not be done even after withdrawal
                        synchronized (this)
                        {
                                notify();
                        }
                        
                        System.out.print("Depositing " + amount);
                        double newBalance = balance + amount;
                        System.out.println(", new balance is " + newBalance);
                        balance = newBalance;
                }
        }

        /**
Withdraws money from the bank account.
@param amount the amount to withdraw
         * @throws InterruptedException 
         */
        public void withdraw(double amount) //throws InterruptedException
        {
                //to check for balance < 0 although it is not mentioned in question but just for reference
                /*if(balance<=0)
                {
                        synchronized (this) 
                        {
                                wait();
                        }
                }
                else
                {
                
                        //no notifying thread so it wake up and does not wait
                        synchronized (this)
                        {
                                notify();
                        }*/
                
                        System.out.print("Withdrawing " + amount);
                        double newBalance = balance - amount;
                        System.out.println(", new balance is " + newBalance);
                        balance = newBalance;
                //}
        }

        /**
Gets the current balance of the bank account.
@return the current balance
         */
        public double getBalance()
        {
                return balance;
        }
}
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
private double balance;
/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{  
balance = 0;
}
/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{  
balance = initialBalance;
}
/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{  
int charge = 1;
double newBalance = balance - amount;
balance = newBalance;
// your work here
balance = balance - charge;
}
/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{  
return balance;
}
}

unchanged class as per question

DepositRunnable. {class}

/**
A deposit runnable makes periodic deposits to a bank account.
 */
public class DepositRunnable implements Runnable
{
        private static final int DELAY = 1;
        private BankAccount account;
        private double amount;
        private int count;

        /**
Constructs a deposit runnable.
@param anAccount the account into which to deposit money
@param anAmount the amount to deposit in each repetition
@param aCount the number of repetitions
         */
        public DepositRunnable(BankAccount anAccount, double anAmount,
                        int aCount)
        {
                account = anAccount;
                amount = anAmount;
                count = aCount;
        }

        public void run()
        {
                try
                {
                        for (int i = 1; i <= count; i++)
                        {
                                account.deposit(amount);
                                Thread.sleep(DELAY);
                        }
                }
                catch (InterruptedException exception) {}
        }
}

unchanged

WithdrawRunnable.java {class}

/**
A withdraw runnable makes periodic withdrawals from a bank account.
 */
public class WithdrawRunnable implements Runnable
{
        private static final int DELAY = 1;
        private BankAccount account;
        private double amount;
        private int count;

        /**
Constructs a withdraw runnable.
@param anAccount the account from which to withdraw money
@param anAmount the amount to withdraw in each repetition
@param aCount the number of repetitions
         */
        public WithdrawRunnable(BankAccount anAccount, double anAmount,
                        int aCount)
        {
                account = anAccount;
                amount = anAmount;
                count = aCount;
        }

        public void run()
        {
                try
                {
                        for (int i = 1; i <= count; i++)
                        {
                                account.withdraw(amount);
                                Thread.sleep(DELAY);
                        }
                }
                catch (InterruptedException exception) {}
        }
}

unchanged

BankAccountThreadRunner. {driver class}

/**
This program runs threads that deposit and withdraw
money from the same bank account.
 */
public class BankAccountThreadRunner
{
        public static void main(String[] args)
        {
                BankAccount account = new BankAccount();
                final double AMOUNT = 100;
                final int REPETITIONS = 100;
                final int THREADS = 100;

                for (int i = 1; i <= THREADS; i++)
                {
                        DepositRunnable d = new DepositRunnable(
                                        account, AMOUNT, REPETITIONS);
                        WithdrawRunnable w = new WithdrawRunnable(
                                        account, AMOUNT, REPETITIONS);

                        Thread dt = new Thread(d);
                        Thread wt = new Thread(w);

                        dt.start();
                        wt.start();
                }
        }
}

Related Solutions

Problem: Add a condition to the deposit method of the BankAccount class, restricting deposits to $100,000...
Problem: Add a condition to the deposit method of the BankAccount class, restricting deposits to $100,000 (the insurance limit of the U.S. government). The method should block until sufficient money has been withdrawn by another thread. Test your program with a large number of deposit threads. (All other classes are provided below) Bank Account.java (This class is the one that needs to be modified) /** A bank account has a balance that can be changed by deposits and withdrawals. */...
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a...
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a BankAccountconstructed from data input from the keyboard. Override ReadAccount in SavingsAccount to return an account that refers to a SavingsAccount that you construct, again initializing it with data from the keyboard. Similarly, implement ReadAccount in the CheckingAccount class. Use the following code to test your work. public static void testCode()         {             SavingsAccount savings = new SavingsAccount(100.00, 3.5);             SavingsAccount s = (SavingsAccount)savings.ReadAccount();...
/* Work to do: 1) add toString method to BankAccount and SavingsAccount classes 2) Override the...
/* Work to do: 1) add toString method to BankAccount and SavingsAccount classes 2) Override the withdraw() in SavingsAccount so that it will not withdraw more money than is currently in the account. 3) Provide constructors for SavingsAccount 4) Add this feature to SavingsAccount: If you withdraw more than 3 times you are charged $10 fee and the fee is immediately withdrawn from your account.once a fee is deducted you get another 3 free withdrawals. 5) Implement the Comparable Interface...
Given the LinkedStack Class as covered in class add a method to the LinkedStack class called...
Given the LinkedStack Class as covered in class add a method to the LinkedStack class called PushBottom which will add a new item to the bottom of the stack. The push bottom will increase the number of items in the stack by 1
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the...
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the phone number that's incremented. Given Files: public class Demo4 { public static void main(String[] args) { SmartPhone test1 = new SmartPhone("Bret", "1234567890"); SmartPhone test2 = new SmartPhone("Alice", "8059226966", "[email protected]"); SmartPhone test3 = new SmartPhone(); SmartPhone test4 = new SmartPhone("Carlos", "8189998999", "[email protected]"); SmartPhone test5 = new SmartPhone("Dan", "8182293899", "[email protected]"); System.out.print(test1); System.out.println("Telephone neighbor: " + test1.getTeleponeNeighbor()); System.out.println(); System.out.print(test2); System.out.println("Telephone neighbor: " + test2.getTeleponeNeighbor()); System.out.println(); System.out.print(test3); System.out.println("Telephone...
1.) A U.S bank pays 2.2% interest on deposits. You deposit $100,000 for 3 months beginning...
1.) A U.S bank pays 2.2% interest on deposits. You deposit $100,000 for 3 months beginning today. What are the proceeds? 2.) A 3 year bond with a face value of 100, pays an annual coupon rate of 10%. If its price is 100, its yield to maturity is: 3.) For an investment of $100 to reach a (future) value of $200 in seven years, it must produce a Compound Annual Growth Rate (implied interest rate) of:
1. what gets printed if anything after executing the main method of class BankAccount below: public...
1. what gets printed if anything after executing the main method of class BankAccount below: public class BankAccount {      private static int masterKey =1;    private String name;      private int accountNumber;      private double balance = 0;      private int age = 1;      public BankAccount (String myName , double balance) {      name = myName;      this.balance = 5 + 2 * balance ;      accountNumber = masterKey;      age++;    masterKey++;    printMe(); } public void...
Please add the following method as a part of the UnorderedList class definition: •print_list: the method...
Please add the following method as a part of the UnorderedList class definition: •print_list: the method prints the elements of the list using the same format as a Python list (square brackets and commas as separators). In the main function of the modified UnorderedList.py, please test the new method to demonstrate that it works as expected. Please leave comments in the code to show what is done UnorderList.py file # Implementation of an Unordered List ADT as a linked list....
What is the issue is in the add method in the SongList Class? It doesn't seem...
What is the issue is in the add method in the SongList Class? It doesn't seem to add the songs when running testing. public class Song { // instance variables private String m_artist; private String m_title; private Song m_link; // constructor public Song(String artist, String title) { m_artist = artist; m_title = title; m_link = null; } // getters and setters public void setArtist(String artist) { m_artist = artist; } public String getArtist() { return m_artist; } public void setTitle(String...
In java, I have problem how to declare BankAccount Account = new BasicAccount(100.00); Given the class...
In java, I have problem how to declare BankAccount Account = new BasicAccount(100.00); Given the class BankAccount , implement a subclass of BankAccount called BasicAccount whose withdraw method will only withdraw money if there is enough money currently in the account (no overdrafts allowed). Assume all inputs to withdraw and the constructor will be valid non-negative doubles. public class BankAccount {     private double balance;     public BankAccount() {         balance = 0;     }     public BankAccount(double initialBalance) {         balance = initialBalance;     }     public...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT