Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a thread code

 
Arun Martin
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
given below is a mock xam question.
question:
--------
public int increment() {
try {
counter += 2;
System.out.write(counter);
}
finally { counter--; }
return counter;
}
What is wrong with method increment()?
options:
--------
* 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()
{
try
{
counter += 2;
System.out.write(counter);
}
finally
{
counter--;

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

rf2 o = new rf2();
o.increment();
}
}
could u please help?
arun.
 
Rob Acraman
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic