Search This Blog

Friday, January 28, 2011

Question 8

What will happen when you attempt to compile and run the following code?

public class TestThread extends Thread{  
  public static void main(String[] args) {
    new TestThread().start();
    new TestThread().start();
  }
  public void run(){
    SafeClass st = new SafeClass("abc");
    SafeClass st1 = new SafeClass("xyz");
  }
}
class SafeClass {
  private String str;
  public synchronized SafeClass(String s){
    str = s;
    str = str.toUpperCase();
    System.out.println(str+" ");    
  }
}
Options :

a. It will print - ABC XYZ ABC XYZ in that sequence.
b. It will print - ABC ABC XYZ XYZ in that sequence
c. It will print - ABC and XYZ twice, but the sequence cannot be determined.
d. It will print - abc and xyz twice, but the sequence cannot be determined.
e. The code will not compile.



Answer : E (The code will not compile).

This is a conceptual question. Java does not allow synchronized keyword to be applied on constructor. I found an interesting explanation on this in the web :


In Java, synchronization of contructors is not allowed (results in a compile time error) as only the thread which is constructing the object should have access to the object and hence any other thread is not granted access until the construction of the object is complete. So, no explicit synchronization needed for constructors.

Question 8SocialTwist Tell-a-Friend

No comments:

Post a Comment