• Post Reply Bookmark Topic Watch Topic
  • New Topic

Lost Update Problem with Concurrent Thread  RSS feed

 
Daniele Barell
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.
I'm reading Head First Java, the part about threads and synchronization.
I'm afraid I didn't get the simple example on "Lost Update" problem.

Here is the code:


which gives a result like:
- Not Synch -
balance 1
balance 3
balance 4
balance 2
balance 6
balance 5
balance 7
balance 8
balance 9
...
balance is not in synch as expected. So far it's ok.

Then the book say to synchronize the 'increment' method to make it atomic.



Which gives me:

- In Synch -
balance 1
balance 2
balance 4
balance 5
balance 3
balance 6
balance 7
balance 8
balance 9
balance 10
balance 12
balance 11
balance 14
balance 15
balance 13
...

But the balance remains unsynchronized.

So what's the point to mark 'increment' method synchronized?
 
Campbell Ritchie
Marshal
Posts: 56197
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you know the synchronisation isn't working? How do you know the problem isn't with System.out; your updates might be correctly synchronised and the printing can be out of time with it. If there is failure to synchronise, you will either get the same value printed twice or one value omitted from the printouts.
 
Daniele Barell
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so, Campbell, is there a method to verify the synchronization?
 
Campbell Ritchie
Marshal
Posts: 56197
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can try adding the balance variables to a List<Integer> every time that method is called. Then see whether each List reads [0, 1, 2...50]
Note the strange code in lines 22‑23 which breaks the increment into two parts, so it is not atomic. Please check in the Java┬« Language Specification whether something like i++; is atomic or not.
 
Daniele Barell
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You can try adding the balance variables to a List<Integer> every time that method is called. Then see whether each List reads [0, 1, 2...50]


Good idea!
Thank you!
 
Serhii Kyrylenko
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In order to see synchronization works properly just move inside method: just right after
Your code increments in synchronized mode, but prints result asynchronously right now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!