Saturday, August 7, 2010


Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 9, Exercise 5

What is the result of trying to compile and run this program?

A. It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 7 

IllegalMonitorStateException is unchecked exception, i.e. it is a runtime exception and by definition cannot be dealt with

B. 1 2 3

3 will never be printed because no thread will notify() the main thread, hence the program will wait forever on line 7

C. 1 3

Same as Option B

D. 1 2

Correct. 1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify() the main thread, so 3 will never be printed. It’s frozen at line 7.

E. At runtime, it throws an IllegalMonitorStateException when trying to wait

Incorrect because IllegalMonitorStateException will never be thrown because the wait() is done on args within a block of code synchronized on args

F. It will fail to compile because it has to be synchronized on the this object
Incorrect. Any object can be used to synchronize on. Keyword this refers to a particular instance of an object, whereas static refers to all instances of an object, hence this and static don’t mix.

No comments:

Post a Comment