• 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
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

Another Threading question from Dan's site

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class A extends Thread {
String[] sa;
public A(String[] sa) {
this.sa = sa;
}
public void run() {
synchronized (sa) {
System.out.print(sa[0] + sa[1] + sa[2]);
}
}
}
class B {
private static String[] sa = new String[]{"X","Y","Z"};
public static void main (String[] args) {
synchronized (sa) {
Thread t1 = new A(sa);
t1.start();
sa[0] = "A";
sa[1] = "B";
sa[2] = "C";
}
}
}

What are the possible results of attempting to compile and run the program?
a. Prints: XYZ.
b. Prints: AYZ.
c. Prints: ABZ.
d. Prints: ABC.
e. Compiler error.
f. Run time error.
g. None of the above.

Correct answer is d: ABC.
My confusion is that in Class B the main() method is synchronizing on String[] sa, which is declared in Class B. And in Class A is the run() method synching up on 'array object sa'(which is declared in Class A) that is diff. from 'String[] sa' in Class B? If thats the case then run() method does not have to wait for the lock release by the main() in Class B?
Thanks,
Sumeer.
 
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sumeer
Yes you are right that if synchronized is called on different objects then the lock is obtained on different objects. But here in this case that's not what's happening. In java we pass a copy of the reference to the object. So when sa gets passed, what is actually passed is a copy of the reference of sa. What's really happening is that sa is used to change the array's contents. Now when you have a reference to an object you can change that object(provided that object is not immutable) and that's what exactly Class A is doing. So when class B obtains a lock on sa it has exclusive right on sa and does whatever changes it needs to do on sa. Then when the lock is released class A's code gets the lock and prints the contents. In this case the lock in both cases is obtained on the same object. If unclear repost.
 
Maybe he went home and went to bed. And took this tiny ad with him:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic