• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized void increment() in [Synchronizing methods/networking and threads/ ch15/HeadFirstJava]  RSS feed

 
Henry de Deaux
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi anyone and everyone!

I implemented the modifier to the class as p.512 of Head First Java seems to suggest.

Without the modifier, the incremental goes mad like 0-0-1-3-2-1- etc. what so ever. I got that part, obviously, thanks to the book. 
With the modifier in the method like , the incremental goes without any  repetition of the same value

but at some point numbers are not linearly progressing, and in my example below :
45-47-48-46-49-50-...
70-72-73-74-75-71-76-...
78-80-79-81-...
85-87-88-86-89-.... the rest is fine. 

Why?
I excepted to be linear incrementation. Is that a multi-core processor problem?
Hint : I ctrl+F for "Now for" in the result display by consol to get the values made by increment().
The other is one, is for me to visualize the path of the thread and the job execution.
Thanks


Source code (with more System.out.println to see the problem)  and print here :


and print:
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The "now for" print statements are not done while owning the lock. So, it is possible for a thread to get the balance, prepare for printing, but ... before it can print, something happens, and the other thread can get a few iterations in, so when the print is done, it is outdated.

Henry
 
Henry de Deaux
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ooooooookay!
Now it seems obvious 
It's why locks are for!!!

Thank you Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!