1

I am attempting the multi-threaded bank transfer problem. However, I am having issues with correctly synchronizing the threads. Periodically after a thread performs a transfer between accounts it will test to ensure no money has been gained or loss altogether.

When a thread enters the test method it is supposed to set a flag that will prevent any other thread from entering the tranfer method, then wait until all threads currently performing transfers to end.

public void transfer(int from, int to, int amount) {        
    //finish running all threads' current transactions before test

    accounts[from].waitForAvailableFunds(amount);
    if (!open) return;    

    //checks to see if any thread is currently testing
    //if so, wait
    while(flag) {
        try {
            wait();
        } catch (InterruptedException e) { /*ignore*/ }
    }

    //do not execute these two statements when a thread
    //is performing a test
    if (accounts[from].withdraw(amount)) {
        accounts[to].deposit(amount);

    }  

    if (shouldTest() && !flag)   test();

}

//only one thread can perform a test at any given moment
public synchronized void test() {        

    //when test starts set a flag telling threads to
    //not begin any new transfers
    flag = true;

    //wait for all threads currently performing transfers
    //to finish current transfer before continuing


    int sum = 0;
    for (int i = 0; i < accounts.length; i++) {
        System.out.printf("%s %s%n", 
                Thread.currentThread().toString(),accounts[i].toString());
        sum += accounts[i].getBalance();
    }
    System.out.println(Thread.currentThread().toString() + 
            " Sum: " + sum);
    if (sum != numAccounts * initialBalance) {
        System.out.println(Thread.currentThread().toString() + 
                " Money was gained or lost");
        System.exit(1);
    } else {
        System.out.println(Thread.currentThread().toString() + 
                " The bank is in balance");
    }

    //reset flag and notify threads test is complete.
    flag = false;
    notifyAll();
}

Firstly, I'm not even positive I have set the flag and waiting correctly. Secondly, how do I have the thread that entered the test method wait for all other threads that are already performing tranfers to complete the current transfer.

Thanks

1 Answers1

0

I think you should use volatile to decorate the flag to make sure it is affected when it is changed in different threads.

Tony Zhu
  • 301
  • 1
  • 6
  • 16