• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

a thread code

 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic