Likes

WCD-LAB @HOME 9-Ans 2

Demonstrate a problem that can arise m a concurrency situation. The project simulates a very simple bank accoimt. modeling only the balance.


Task - Witness the Failure

1. Open the project SL3i4m09labi in the d:\labs\student\exercises director}- and nin the project.
2. In your browser, select Deposit and deposit 100. then select Withdraw and withdraw 50 from the account. Satisfy yourself that the project is capable of the essential computation for this simulation.
3. Open a second tab in your browser, and load the base page of the application in that too. It should show the same balance that was left after step two.
4. Without clicking Submit yet m either tab. set one tab up to deposit 100 and the other to withdraw 200.
5. In less than five seconds, click Submit on both tabs. When the pages return, notice that each shows a balance that would have been correct if the other operation had not occurred, but is wrong for the aggregate of both operations.
6. In either of the tabs, deposit a zero amount. Notice that the balance shown is definitely wrong.
Task - Examine the Cause of the Failure

1. Open the domain.Account class in the XetBeans editor wmdow.

2. Observe that m the deposit and withdraw methods, the computation consists of:
a. Read the balance
b. Modify the balance
c. Store the new balance
This logic is correct, however, a delay has been deliberately added after step a. this means that if two threads execute these methods concurrently, each will start with the unmodified balance, and then write it back. In effect, the last one to complete wins. This is called a write-write conflict.

3. Consider how you might fix this problem. Unfortunately, the solution of removing the sleep, and of modifying the code to read this. balance += amount does not solve the problem. It greatly reduces the chance that you will see it. especially m a lab environment with one user testing the code, but it is not a correct solution. The problem remains that the execution of the += operator still involves reading the value, modifying it. and then stormg the result. Although the tune delay between the read and the write is small, it is not zero.
In effect, whenever variable data are shared between threads, this kind of problem might arise. A ftill solution may often be achieved us mg synchronization or database transactions, however, details of these are beyond the scope of the class.

4. Modify the methods deposit and withdraw by marking them synchronised. Do not remove or alter any of the existing code.

5. Rim steps 3 and 4 from Task 1 above again. Notice this time that the simulation takes longer to complete, but the answer is correct.

No comments: