I've been trying to understand some of the new features of java.util.concurrent and I'm getting somewhat confused.
I created a basic class to represent a bank account, with simple methods to check the balance and withdraw. I then wrote three
test classes. Each class ran ten threads sharing a common account; each
thread would check the balance and, if it was greater than zero it would withdraw 1. When the balance reaches zero the test ends.
Test 1) No synchronization. Inevitably the account goes overdrawn.
Test 2) Wrapping the get balance and withdraw commands inside a synchronized(account) { ... } block
Test 3) As above, using the ReentrantLock class instead of synchronized.
Q1) Test 1 takes anything from 10% up to 100% longer to run than tests 2 or 3. It's very inconsistent - why might that be?
Q2) Test 2 is typically 10% quicker than Test 3. Why? I thought the idea was that the ReentrantLock was supposed to be quicker/lighter than a synchronized block?
Source code available on request. Written and tested using NetBeans 4.1 and HotSpot 1.5.0_04-b05 under Windows XP on an Athlon.