Thursday 15 April 2010

java - Synchronization while using AtomicInteger -


Suppose I want to implement a very simple bank account class, and we Want to take care about concurrency and multi-threading problems?

What is the balance atomicator ?

On the other hand, if we have all the synchronized methods, then AtomicInteger will no longer be used anymore, right? Import java.util.concurrent.atomic.AtomicInteger; Public Class Account {Atomic Integer Balance; Public synchronized int check balance () {return.balance.intValue (); } Public Synchronized Deposit (Int.) {Balance.getAndAdd (Amount); } Public synchronized bullion substantial fund (int a) {if (balance.intValue ()> = a) return true; return false; } Public synchronized boolean transfer_funds (account ACC, int zodiac) {// dest: ACC if (sufficient fund (amount)) {return (amount); Acc.deposit (amount); Back true; } return false; } Back to public synchronized boolean (int.) {If (check balance () & lt; amount) return false; Balance.get and Junk (-1 * amount); Back true; }}

declared your amount as AtomicInteger Has been prevented from being threaded (if it is not synchronized) by being preempted in between execution. For example, if your method transfer_funds was not synchronized in any way, you can get unexpected results, even if your amount is AtomicInteger < Pre> public / * synchronize * / boolean transfer_funds (account acc, int zodiac) {// dest: ACC if (ample funds (amount)) {back (amount); // & lt; - Thread method execution can be preempted between acc.deposit (amount); Back true; } return false; }

Such problems are called race conditions. A possible example is when two threads attempt to transfer funds from the same account. When a thread determines that is sufficient funds to transfer the credit, this thread can be prepaid and at the same time other threads can transfer funds from this account. When the first thread starts processing again, there is no enough fax to transfer the credit, so it does not double check (it has already checked it, but its knowledge May be outdated), but it goes in the next line to execute. In this way you can not get results consistently. At the beginning of all accounts you have the total amount can be changed.

The core Java Book has a very good description of this aspect in the Java Book - available here for free, it explains the problem of the same type of detail that you are asking.

No comments:

Post a Comment