Why are threads still inconsistent?

I have a java code that mimics bank transfers. The account class simply has a balance field and a transfer method that add balance to the balance field.

TransferManager defines the Transfer class, which takes two Account objects to transfer a given amount from one account to another, which is passed as parameters.

The Manager himself has two important methods that need to be synchronized, because both of them work on the same resource, and they will be called in a thread-wise way:

public synchronized void issueTransfer(Account from, Account to, int amount) {
    openTransfers.add(new Transfer(from, to, amount));
    issuedTransfers++;
}

public synchronized void performTransfers() {
    for(Transfer transaction : openTransfers) {
        transaction.performTransfer();
            performedTransfers++;
    }       
    openTransfers.clear();
}

Without a synchronization instruction, I get NullPointerExceptions in an arraylist where Transfers are stored and read.

BankTest 10 , 10 . BankTest.java. , 10 * 10 . 98 99:

enter image description here

BankTest.java? ? ?

TransferManager.java: http://pastebin.com/Je4ExhUz

BankTest.java: http://pastebin.com/cdpWhHPb

Exersice3.java: http://pastebin.com/v7pwJ5T1

Account.java: http://pastebin.com/QYEeWy5Z

+1
2
try {
    Thread.sleep(60);
} catch (InterruptedException e) {
    e.printStackTrace();
}

.

try {
    for(Thread thr:threads)thr.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}
+4

?

openTransfers.add openTransfers. , , ( ), . 2 1 1 .

, . 10 size = size + 1, size 1 10. , 99 . , size 99, , 99 , 100 98 1.

, . , .

+1

All Articles