Problem

Visit www.myprogramminglab.com to complete select exercises online and get instant feedbac...

Visit www.myprogramminglab.com to complete select exercises online and get instant feedback.

Exercise

This program simulates what might happen if two people who share the same bank account happen to make a simultaneous deposit or withdrawal and the bank does not account for race conditions by recreating the situation described in Displays 1 and 2 with a simple BankAccount class. The BankAccount class should store an account balance and have methods to retrieve the balance, make a deposit, and make a withdrawal. Do not worry about negative balances.

Next, create an array of thousands of threads where each thread has a reference to the same BankAccount object. In the run() method, even numbered threads deposit one dollar and odd numbered threads withdraw one dollar. If you create an even number of threads, then after all threads are done the account balance should be zero. See if you can find a number of threads so that you consistently end up with a balance that is not zero. If you want to increase the likelihood of a race condition, then make each thread sleep a short random number of milliseconds in the run() method.

Add the synchronized keyword to fix the problem and ensure a balance of zero after all the threads are done.

Display 1 The Counter Class

Display 2 The RaceConditionTest Class (part 1 of 2)

Display 2 The RaceConditionTest Class (part 2 of 2)

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
Solutions For Problems in Chapter 19