These days, I am reading the book Core Java and I was confused when I read Concurrency Chapter. There is one example of the synchronized block, here is the segment:
[![oij]](../../images/3826060443.webp)
My understanding of the marked sentence is that If the get method of Vector is not synchronized or I don't hijack the lock of 'accounts', this transfer method will not be thread safe.
Then I write some test code.And I use another lock without hijacking the lock.But the result is opposite of my understanding.
The following is my code.
public class VectorBank {
public void transfer(Vector<Integer> accounts, int from, int to, Integer amount) {
synchronized (this) {
if (accounts.get(from) < amount) return;
accounts.set(from, accounts.get(from) - amount);
accounts.set(to, accounts.get(to) + amount);
System.out.println(getTotalBanlance(accounts));
}
}
public Integer getTotalBanlance(Vector<Integer> accounts) {
Integer sum = new Integer(0);
for (Integer a : accounts) {
sum += a;
}
return sum;
}
}
the test class:
public class VectorBankTest {
public static final int MAX_AMOUNT = 1000;
public static final int DELAY = 10;
public static final int NACCOUNTS = 100;
public static final int INITIAL_BALANCE = 1000;
public static void main(String[] args) {
Vector<Integer> accounts = new Vector<>();
for (int i = 0; i < NACCOUNTS; i++) {
accounts.add(INITIAL_BALANCE);
}
VectorBank bank = new VectorBank();
for (int i = 0; i < NACCOUNTS; i++) {
int fromAccount = i;
Runnable r = () -> {
try {
while (true) {
int toAccount = (int) (accounts.size() * Math.random());
int amount = (int) (MAX_AMOUNT * Math.random() + 1);
bank.transfer(accounts, fromAccount, toAccount, amount);
Thread.sleep((int) (DELAY * Math.random()));
}
} catch (InterruptedException e) {
System.out.println("Do nothing!");
}
};
Thread t = new Thread(r);
t.start();
}
}
}
and the result make me confused.I synchronized all thread successfully, the total banlance of all accounts is always 100000.
[![awef]](../../images/3799714887.webp)
So my exact problem is, what indeed can a synchronized block do? And what does 'hijack a lock' really mean?