• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sybex book: p.276. Synchronization issue.

 
Mikalai Zaikin
Ranch Hand
Posts: 3371
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Ranchers.
Can you examine the following code? It's stated in the book that it is thread-safe :

I don't see almost any difference if I delete
synchronized(this) block. Incrementation will be atomic always (Ok, almost always), but after thread will leave - we can not expect value of instance variable, so when printing happens value will be unexpected, because other thareads can modify value between

and
 
friso jonge
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
true, i read that as well and had the same thoughts.... (and still have). So if someone can clear this up
 
Sam Dalton
Author
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by friso jonge:
true, i read that as well and had the same thoughts.... (and still have). So if someone can clear this up

It is excatly as you say. You would need to contain the println within the sysnc block to guarantee that the value printed is the one that you just incrememented it to.
Cheers
Sam
 
k space
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To me, thread-safe means you are not updating something with incorrect value due to multiple threads running at the same time;
In this example, if we don't put synchronized(this) around count++. It may happen that two threads try to increment the count at the same time. They may both obtain the same initial value (e.g. 0) and set it to 1. But 1 is not the correct answer, because we have two increments here.
Whether you want the print to synchronise with the updated value or not? This is another story.
In this case, one will say 1, and another reports 2. It is completely fine to me, as I cannot tell which thread goes first.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic