Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Question about synchronization  RSS feed

 
Adrian Cordoba
Greenhorn
Posts: 26
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, all!
I've been studying concurrent programming from Oracle Documentation. And I was testing some code from that tutorial:
I have a class with a field that can be incremented or decremented:

And two Thread classes for create threads: One of them for increment the Counter's value, and the other one for decrement it:


Finally, I coded a main class that creates two threads (IncrementThread and DecrementThread) with the same Counter object, and start them:

I understand when I run this little application that the printed values in console are not consistent:

Decrement thread: value = 8385
Increment thread: value = 8388
Increment thread: value = 8385
Increment thread: value = 8386
Increment thread: value = 8387
Decrement thread: value = 8384
Increment thread: value = 8388


But, what I cannot understand is that something similar happens when I synchronize the access methods to the field "value" of the Counter class (Synchronized Methods):

With synchronized methods I get the same thing:

Decrement thread: value = 1989
Decrement thread: value = 1988
Decrement thread: value = 1987
Decrement thread: value = 1986
Increment thread: value = 1990
Decrement thread: value = 1985
Decrement thread: value = 1985
Decrement thread: value = 1984


Can someone tell me what's happening?
(Details are welcome.)

Thank you, in advance.
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You seem to assume that lines 11 and 12 of the DecrementThread and IncrementThread are executed atomically, but they're not. It's perfectly possible (likely, in fact), that threads are switched between lines 11 and 12.
 
Adrian Cordoba
Greenhorn
Posts: 26
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Dittmer wrote:You seem to assume that lines 11 and 12 of the DecrementThread and IncrementThread are executed atomically, but they're not. It's perfectly possible (likely, in fact), that threads are switched between lines 11 and 12.


Thank you, Ulf Dittmer.
Now, I understand.
 
Andrew Suckerman
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand. Can anyone explain details please?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!