Page 1 of 1
About Question com.enthuware.ets.scjp.v6.2.642 :
Posted: Sat Feb 26, 2011 4:26 pm
by ETS User
Which of the following statements are true?
Selection 3 is:
synchronized keyword may be applied to a non-primitive variable.
... you are saying that this is not true. Your explanation is:
It can only be applied to a method or a block.
Consider this code:
Code: Select all
public class WaitTest {
public static void main(String[] args) {
System.out.print("1 ");
synchronized(args){
System.out.print("2 ");
try {
args.wait();
}
catch(InterruptedException e){}
}
System.out.print("3 ");
}
}
This code does not generate any compiler errors and does not throw any exceptions when run. The result of a run of this code is "1 2"
Isn't args considered a non-primitive variable (an array object) and, if so, doesn't the code synchronize on that non-primitive variable? Please help me understand your position.
Thank you.
Re: About Question com.enthuware.ets.scjp.v6.2.642 :
Posted: Sat Feb 26, 2011 7:22 pm
by admin
I think it is about how you interpret the statement "apply to something". In the code that you've posted, you are applying synchronized to a block. You are using an object to synchronize but you are not synchronizing the object. You synchronize on an object, you don't synchronize the object. Synchronizing an object (i.e. a non-primitive variable) doesn't make sense.
In that sense, applying synchronized to a non-primitive would be something like (which will not compile):
private synchronized String str;
or
synchronized Object obj;
This is similar to how you apply synchronized to a method:
public synchronized void m(){
}
.