Problem : Write a program that creates two threads. Both deposit 5000 Rs in the same account and go into racing condition. Account.deposite() method is made synchronized so that only one thread can have access on it at a time, otherwise you will get incorrect balance. You can experience incorrect balance if you remove synchronized keyword. Program :Step 1 - CodingCreate a text file c:\sunilos\Account.java and copy below contents./* * A program implements Racing Condition */ public class Account { private int balance = 0; //public synchronized void deposit(String message, int amount) { /* Comment below statement and uncomment above statements to make deposit method synchronized and get correct balance amount. */ public void deposit(String message, int amount) { int bal; bal = getBalance() + amount; setBalance(bal); System.out.println(message + " Now Balance is " + bal); } public int getBalance() { try { Thread.sleep(200); // Simulate Database Operation } catch (InterruptedException e) { } return balance; } public void setBalance(int balance) { try { Thread.sleep(200);// Simulate Database Operation } catch (InterruptedException e) { } this.balance = balance; } } Step 2 - Creating Test ProgramCreate a text file c:\sunilos\RacingCondThread.java and copy below contents. /* * A program implements Racing Condition */ public class RacingCondThread extends Thread { public static Account data = new Account(); private String name = null; public RacingCondThread(String name) { this.name = name; } public void run() { for(int i=0;i<5;i++){ data.deposit(name, 1000); } } public static void main(String[] args) { RacingCondThread user1 = new RacingCondThread("Dhoni"); RacingCondThread user2 = new RacingCondThread("Yuvraj"); user1.start(); user2.start(); } } Step 3 - Deployment
Step 4 - Testing
OutputWhen method is not synchronizedpublic void deposit(String message, int amount) { Dhoni Now Balance is 1000 Yuvraj Now Balance is 1000 Dhoni Now Balance is 2000 Yuvraj Now Balance is 2000 Dhoni Now Balance is 3000 Yuvraj Now Balance is 3000 Yuvraj Now Balance is 4000 Dhoni Now Balance is 4000 Yuvraj Now Balance is 5000 Dhoni Now Balance is 5000 When method is synchronized public synchronized void deposit(String message, int amount) { Dhoni Now Balance is 1000 Dhoni Now Balance is 2000 Dhoni Now Balance is 3000 Dhoni Now Balance is 4000 Dhoni Now Balance is 5000 Yuvraj Now Balance is 6000 Yuvraj Now Balance is 7000 Yuvraj Now Balance is 8000 Yuvraj Now Balance is 9000 Yuvraj Now Balance is 10000 FAQQ: How may types of synchronization are there?A: Two type of synchronization 1. Method public synchronized void deposit(String message, int amount) {…. 2.Block public void deposit(String message, int amount) { synchronized (this){ int bal = getBalance() + amount; } setBalance(bal); System.out.println(message + " Now Balance is " + bal); |