Hello I have a Java application that takes an input number of operations to perform and it run different threads for each operation:
//create operations to execute
Thread t[] = new Thread [n_operations];
//we create a Bank with N accounts
Bank mybank = new Bank(N);
//execute a separate thread per operation
for (int i = 0; i < n_operations; i++) {
int id = i;
Operation o = new Operation(mybank, id);
t[i]= new Thread (o);
t[i].start();
}
for (int i=0;i<N;i++){
try{
t[i].join();
}catch(Exception e){;}
}
Now I need to perform concurrent transfer on the accounts, where the Bank class is defined like this:
public class Bank {
private static Account[] accounts;
final int MAX_balance = 100000;
int MAX_accounts = 0;
/* Create accounts of a bank */
public Bank (int N) {
accounts = new Account[N];
MAX_accounts = N;
for (int i = 0; i < N; i++)
accounts[i] = new Account (i, 1000);
}
public int getN(){
return MAX_accounts;
}
public synchronized int transfer(int from, int to, int amount) {
synchronized (accounts[from]){
synchronized (accounts[to]){
if (accounts[from].balance () < amount) {
try{
System.out.println("Error during transfer: Not enough Money");
}
catch(Exception err){
return 1;
}
}
accounts[from].sub(amount);
accounts[to].add(amount);
}
}
return 0;
}
}
When the program performs the operations:
public class Operation implements Runnable {
private Bank b;
int id;
Random r;
private final int MAX_TRANSFERENCIAS = 1000;
public Operation (Bank b, int id) {
this.b = b;
this.id = id;
}
public int syncronize(){
return 1;
}
public void run () {
r = new Random();
if(b == null)
throw new RuntimeException("b is null!");
if(r == null)
throw new RuntimeException("r is null!");
int max = b.getN();
//depend if there is a conflict or not
b.transfer (id,r.nextInt(max),r.nextInt(100));
}
}
I get a series of errors like this message:
at Bank.transfer(Bank.java:28) /* which is "synchronized (accounts[from]){" */
at Operation.run(Operation.java:33) /* which is "b.transfer
(id,r.nextInt(max),r.nextInt(100));" */
at java.lang.Thread.run(Unknown Source)
java.lang.ArrayIndexOutOfBoundsException: 4714
Do you think the Synchronization is ok?
Any suggestions? Many thanks
UPDATE (I can't answer myself)
There is a concept error in the main loop (for i..to n_operations), the function is passing "int id = i;" as parameter for the source_account, while the n_operation number is bigger than the max value of the array, so the compiler reasonably says: ArrayIndexOutOfBoundsException.
As final contribution I would ask you to kindly check if the Synchronization is done correctly, as I am not an expert in multithreading. Many thanks again, and sorry for badly formulate the question this morning....