We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

threads data corruption

gudii9
gudii9 asked
on
Medium Priority
328 Views
Last Modified: 2012-05-11
>>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.
Comment
Watch Question

Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Mick BarryJava Developer
CERTIFIED EXPERT
Top Expert 2010
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.