• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization problem  RSS feed

 
Shouvik Bhattacharya
Ranch Hand
Posts: 40
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




I am unable to understand why my output is wobbling between threads one and two when I have a synchronized method go()...........whichever thread executes first gets to execute the synchronized method hence acquires the lock on new change() instance so it should be the first one to complete in a orderly manner.......it is only after the first thread is done executing synchronized method the other thread can enter it again.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The two threads are synchronizing on different objects. Declaring a method synchronized makes it synchronize on the current object instance (Change in this case). And since each run() call creates a new Change object, there is effectively no synchronization.

Alter your code like this and see what happens:
 
Shouvik Bhattacharya
Ranch Hand
Posts: 40
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Dittmer wrote:
Alter your code like this and see what happens:


Okay I did as you said and now both the threads effectively act on the same instance. Just want to clarify one small doubt in the modified code when we call myChange.go() so this time the thread will effectively synchronize on the object referred to by the myChange reference variable i.e. the threads operate on the same instance(new Change()) is my understanding correct?
 
Henry Wong
author
Sheriff
Posts: 23284
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
Shouvik Bhattacharya wrote:
Okay I did as you said and now both the threads effectively act on the same instance. Just want to clarify one small doubt in the modified code when we call myChange.go() so this time the thread will effectively synchronize on the object referred to by the myChange reference variable i.e. the threads operate on the same instance(new Change()) is my understanding correct?


Ulf version of the class creates one Change instance, and synchronized on it. Your version of the class creates two Change instances, and "synchronizes" on different instances. That is the key difference.

The fact that Ulf chosen to use an instance reference variable is moot. He could have done it in a totally different way -- the key is that there is only one instance, and it is the same instance used by both threads.

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