• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads confusion

 
Ranch Hand
Posts: 58
Firefox Browser Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 2419
13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic