Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

java - Synchronization while using AtomicInteger

Let's assume that I want to implement a very simple Bank Account class , and we want to take care about concurrency and multi-threading issues,

Is it a good idea to make the following methods synchronized even though balance is AtomicInteger ?

On the other hand , if we have all the methods as synchronized , there would be no use of AtomicInteger anymore , right ?

import java.util.concurrent.atomic.AtomicInteger;


public class Account {
    AtomicInteger balance;
    public synchronized int checkBalance(){
        return this.balance.intValue();
    }
    public synchronized void deposit(int amount){
        balance.getAndAdd(amount);
    }
    public synchronized boolean enoughFund(int a){
        if (balance.intValue() >= a)
            return true;
        return false;
    }
    public synchronized boolean transfer_funds(Account acc, int amount){ // dest : acc 
        if (enoughFund(amount)){
            withdraw(amount);
            acc.deposit(amount);
            return true;
        }
        return false;
    }
    public synchronized boolean withdraw(int amount){
        if (checkBalance() < amount)
            return false;
        balance.getAndAdd(-1 * amount);
        return true;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes for both, it is a good idea to make it synchronized, and Atomic is not needed.

If you rely simply on Atomic instead of synchronization, you can have issues such as in this method:

    if (enoughFund(amount)){
        withdraw(amount);
        acc.deposit(amount);
        return true;
    }

because Atomic only guarantees that your integer will be safe from simultaneous access, which means enoughFund(amount) will be guaranteed to provide a correct value for amount even if it is being written by some other thread. However, Atomic alone does not guarantee that the value obtained at this line would be the same as in the next line of code, because the other thread could execute another Atomic operation in between these two lines, resulting in withdraw(amount); being able to set your balance below zero.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...