File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes a thread code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "a thread code " Watch "a thread code " New topic

a thread code

Arun Martin
Ranch Hand

Joined: Dec 01, 2000
Posts: 64
given below is a mock xam question.
public int increment() {
try {
counter += 2;
finally { counter--; }
return counter;
What is wrong with method increment()?
* the "finally" code block must include a return statement
* the method should be synchronized
* there is no "catch" block
* outputstream "out" must be opened inside increment()
* finally() can not access class variables
i tried revamping the code and it is successfully working(ie no output is being displayed) but even then i don't have any clue to what the correct answer is.
revamped code:
class rf2
int counter=0;
public int increment()
counter += 2;

return counter;
public static void main(String a[])

rf2 o = new rf2();
could u please help?
Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
Wel,, since you've successfully compiled and run the code, you've effectively ruled out options A,C,D and E - leaving B "method should be synchronized".
increment() is both reading and re-setting a class variable, which makes it especially prone to weird results if another thread just happens to invoke increment() on the same object at the same time. OK, unlikely but possible (and it's pretty difficult to consistently generate this test-case).
This could be considered being over-the-top, but then just adding "synchronized" is a very simple step for peace-of-mind.
It is sorta covered in the JavaRanch Style Guide.
subject: a thread code
Similar Threads
Which executes first? ++ Operator Question.
where to use return statement
COnfusion About Unreachable Code
try, catch,finally
Stack over flow error not in try/finally block