threads data corruption

>>The following code is an attempt to illustrate how important it is to synchronize threads that might access the same data. It consists of a class called bank, that acts as a driver to create multiple threads of running the methods of a class called Business. The Business threads act to add and subtract money from the accounts. The idea of the code is to illustrate how multiple threads can "tread on each others toes" and lead to data corruption, even though there is code that attempts to avoid this corruption. In order to "fix" and ensure this corruption I have put in a call to a sleep method, which you can consider to be the equivalent to the pause that would take place when real banking code wrote to a database. The corruption that this illustrates would still occasionally happen without this call to sleep but you might have to run the code quite a few times and for quite a long time before it manifested itself.

public class Account{
    private int iBalance;
    public void add(int i){
    iBalance = iBalance + i;
    System.out.println("adding " +i +" Balance = "+ iBalance);
    }
    public  void withdraw(int i){
    if((iBalance - i) >0 ){
        try{
        Thread.sleep(60);
        }catch(InterruptedException ie){}
        iBalance = iBalance - i;
    }else{  
        System.out.println("Cannot withdraw, funds would be < 0");
    }      
    if(iBalance  < 0){
        System.out.println("Woops, funds below 0");  
        System.exit(0);
    }
   
    System.out.println("withdrawing " + i+ " Balance = " +iBalance);
    }
    public int getBalance(){
    return iBalance;
    }
}





I read above program and explanation from link
http://www.jchq.net/certkey/0703certkey.htm

It is not clear to me in tems of flow, use of synchronized, data corruption.





Any ideas, resources, links, sample code highly appreciated. thanks in advance.
LVL 7
gudii9Asked:
Who is Participating?
 
objectsConnect With a Mentor Commented:
Say the balance of the account is 100
Then two threads at the same time try to call withdraw(100)
you will end up with the account being overdrawn

to stop this possibility we could synchronize the withdraw method so only one thread can call it at a time
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.