Win a copy of Spring Boot in Practice this week in the Spring forum!
  • 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic