About Question com.enthuware.ets.scjp.v6.2.642 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
ETS User

About Question com.enthuware.ets.scjp.v6.2.642 :

Post 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.

admin
Site Admin
Posts: 10053
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.ets.scjp.v6.2.642 :

Post 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(){
}
.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 40 guests