Question: Is my code creating a deadlock? If not, how can I create one that does? 1 package synch2; 2 3 import java.util.*; 4 10 public

Is my code creating a deadlock? If not, how can I create one that does?

 1 package synch2; 2 3 import java.util.*; 4 10 public class Bank 11 { 12 private final double[] accounts; 13 19 public Bank(int n, double initialBalance) 20 { 21 accounts = new double[n]; 22 Arrays.fill(accounts, initialBalance); 23 } 24 25 /** 26 * Transfers money from one account to another. 27 * @param from the account to transfer from 28 * @param to the account to transfer to 29 * @param amount the amount to transfer 30 */ 31 public synchronized void transfer(int from, int to, double amount) throws InterruptedException 32 { 33 while (accounts[from] < amount) 34 wait(); 35 System.out.print(Thread.currentThread()); 36 accounts[from] -= amount; 37 System.out.printf(" %10.2f from %d to %d", amount, from, to); 38 accounts[to] += amount; 39 System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); 40 notifyAll(); 41 } 42 43 /** 44 * Gets the sum of all account balances. 45 * @return the total balance 46 */ 47 public synchronized double getTotalBalance() 48 { 49 double sum = 0; 50 51 for (double a : accounts) 52 sum += a; 53 54 return sum; 55 } 56 57 /** 58 * Gets the number of accounts in the bank. 59 * @return the number of accounts 60 */ 61 public int size() 62 { 63 return accounts.length; 64 } 65 }

package deadlockapp;

public class DeadlockApp { public static final int NACCOUNTS = 5; public static final double INITIAL_BALANCE = 1000; public static final double MAX_AMOUNT = 3 * INITIAL_BALANCE; 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(fromAccount, toAccount, amount); Thread.sleep((int)(DELAY * Math.random())); } } catch (InterruptedException e) { } }; Thread t = new Thread(r); t.start(); } } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!