Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads confusion

 
sarvesh dikonda
Ranch Hand
Posts: 58
Firefox Browser Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The below code is from the Threads chapter from SCJP 6 Study Guide-

Snippet 1:


And the question asked is:-
Which of the following pairs of method invocations could NEVER be executing at the same time?
A. x.a() in thread1, and x.a() in thread2 & there are other options too.

But, i just want to clarify the concept that is associated with the one given in option A.
In the book, the explanation given associated with option A is -
A is a right answer because when synchronized instance methods are called
on the same instance, they block each other.

So my doubt is that, from the above explanation, can i conclude that, each thread(i.e thread1 & thread2) are having same copy of object pointed by 'x' that are invoking the synchronized instance method a() ? I am asking this because i am getting confused with the code below.

Snippet 2:


From the above code, both the Threads are using the same or different instance(s) of Dudes as 'd' is marked static which is accessing the synchronized method from Dudes. I am thinking that, if the quoted statements(i.e
A is a right answer because when synchronized instance methods are called
on the same instance, they block each other.
) mentioned above from Snippet 1, is followed for this Snippet 2, then both the Threads here too must block each other, but it does not!

I know there is some difference between Snippet 1 & Snippet 2. But i want to clarify my doubt. So i need your guidance friends.
 
Himai Minh
Ranch Hand
Posts: 1296
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For code snippet 1, two threads share the same runnable instance. The runnable instance only has one x instance. Two threads share the same x.
The x instance's a method is synchronized. So, two threads access a method of x instance one at a time, not concurrently.

For code snippet 2, there are two DudesChat instances. But they share the same d instance. Since d instance's chat method is synchronized, only one DudesChat instance access chat method one at a time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic