Question: Modify the following Java program (Deadlock) in such a manner that it will no longer generate a deadlock. the program needs to accomplish the same
Modify the following Java program (Deadlock) in such a manner that it will no longer generate a deadlock. the program needs to accomplish the same basic functionality but prevents deadlocks.
code with deadlock example is shown below.
Class 1
package deadlocks;
public class Deadlock{
public static final int NACCOUNTS = 100; public static final double INITIAL_BALANCE = 1000; public static final double MAX_AMOUNT = 1000; public static final int DELAY = 10;
public static void main(String[] args) { Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE); for (int i = 0; i < NACCOUNTS; i++) { int fromAccount = i; Runnable r = () -> { try { while (true) { int toAccount = (int) (bank.size() * Math.random()); double amount = MAX_AMOUNT * Math.random(); bank.transfer(toAccount, fromAccount, amount); } } catch (InterruptedException e) { } }; Thread t = new Thread(r); t.start(); } }
}
Class 2 package deadlocks;
import java.util.Arrays; import java.util.concurrent.locks.*;
class Bank { private final double [] accounts; private Lock banklock = new ReentrantLock(); private Condition sufficientFunds = banklock.newCondition();
public Bank(int n, double initialBalance) { accounts = new double[n]; Arrays.fill(accounts, initialBalance); } public void transfer(int from, int to, double amount) throws InterruptedException { banklock.lock(); try { while(accounts[from] sufficientFunds.await(); } System.out.print(Thread.currentThread()); accounts[from]-=amount; System.out.printf("%10.2f from %d to %d", amount, from, to); accounts[to]+=amount; System.out.printf("Total Balance: %10.2f%n", getTotalBalance()); sufficientFunds.signal(); }finally{ banklock.unlock(); } } public double getTotalBalance(){ banklock.lock(); try{ double sum = 0; for(double a: accounts){ sum+=a; } return sum; }finally{ banklock.unlock(); } } public int size(){ return accounts.length; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
