Without any synchronization, doTransaction1(), we can see that every account was corrupted.
For example, the balance of account number 0 was reported as 1051.87 by the
BankingMain class, but it should be 465.73, which is the sum of balances
from all the threads on account number 0.
With the synchronized method, doTransaction2(), the balances in the BankingMain class were
maintained perfectly correct, but the performance of the threads were reduced
dramatically. Without synchronization, BnakingThread was performing about
444 transactions in 5 seconds. But with the synchronized method, it was performing
only about 169 transactions.
By moving the synchronization from the method level to statements level,
doTransaction3(), the performance improved slightly, from 169 transactions to 172
transactions.
By replacing the central lock, o_lock, with individual locks per account, a_lock[i],
the performance improved dramatically, from 172 transactions to 281 transactions.
With the central lock, we were putting all other threads on hold while one thread
was running the synchronized block. With the individual locks, we were putting only
other threads on hold if they happened to work on the same account number as the thread
who was running the synchronized block. The chance of this situation is only about
1 over the number of accounts. As the number of accounts increases, the BankingThread
will perform better and better.
Exercise: Assuming the following class is used in a multiple-threaded program:
public class C {
public static synchronized void m1() {
statement block_1
}
public synchronized void m2() {
statement block_2
}
public synchronized void m3() {
statement block_3
}
public void m4() {
synchronized (this) {
statement block_4
}
}
}
Is it possible that block_1 in one thread could be on hold because of block_1
is running another thread?
Is it possible that block_1 in one thread could be on hold because of block_2
is running another thread?
Is it possible that block_2 in one thread could be on hold because of block_1
is running another thread?
Is it possible that block_2 in one thread could be on hold because of block_2
is running another thread?
Is it possible that block_2 in one thread could be on hold because of block_3
is running another thread?
Is it possible that block_2 in one thread could be on hold because of block_4
is running another thread?