Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization doubt: K&B Chp 9, p707

 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If two threads are about to execute a synchronized method in a class, and both thread are using the same instance of the class to invoke the method, only one thread at a time will be able to execute the method.


For my code below, the main thread is doing fine, printing what I expected.

But when I started the other threads (A and B), their results are different.



Output is:



I'm expecting that the output for A and B will be like this:

Instead of the same results as the main thread (nicely ordered 1-2-3 printouts), A and B printouts seem intertwined.

What gives?
 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even if I add a new class that implements Runnable and assigns it to the new thread, I'm still getting the same output.

 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The problem is at the lines that I have marked. Both the threads are using separate instances of the SyncClass class. You should modify this code as-
 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!

I got the idea so I changed it into something like my 2nd post above. However, the printout is still the same. What I did was,

SyncClass - just ordinary class with the synchronized method.
SyncJob - the Runnable class where SyncClass is instantiated and the synchronized method is called.

And then I realized that I'm still creating two different instances for the threads when the run is called. So I made the SyncClass the Runnable class instead, and removed the SyncJob totally.



The output is OK now. However this is not the design I want. I like to call a synchronized method from other classes that don't implement Runnable, and then see the actual synchronizing take effect. Any idea for this?
[ August 12, 2008: Message edited by: Denise Saulon ]
 
Vinod Kumar Kommineni
Ranch Hand
Posts: 54
Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key is for an object not for a method .
so if two threads are running on the same object you will get your output.


check the code above .
you will get the output you expected.
 
Denise Advincula
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it now! Thank you for all your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic