File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from PGJC Exam

 
Sahul Yasin
Ranch Hand
Posts: 48
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following code, which statements concerning the objects referenced through the member variables i, j and k are true, given that any thread may call the methods a(), b() and c() at any time?
class Counter {
int v = 0;
synchronized void inc() { v++; }
synchronized void dec() { v--; }
}
public class Q7ed5 {
Counter i;
Counter j;
Counter k;
public synchronized void a() {
i.inc();
System.out.println("a");
i.dec();
}
public synchronized void b() {
i.inc(); j.inc(); k.inc();
System.out.println("b");
i.dec(); j.dec(); k.dec();
}
public void c() {
k.inc();
System.out.println("c");
k.dec();
}
}
Select 2 correct answers
1. i.v guaranteed always between 0 and 1
2. j.v guaranteed always between 0 and 1
3. k.v guaranteed always between 0 and 1
4. j.v will aways be greater than or equal to k.v at any time
5. k.v will aways be greater than or equal to j.v at any time
 
David Hadiprijanto
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mohamed,
the code seems to be incomplete, however, I think the answers are 1 and 2.
The key I think is the fact that c() is not synchronized, so 3 will be false. And 5 is definitely false since in b(), there is a moment where k will be less than j. And 4 can also be shown to be false because c() is not synchronized.
Hope this helps.
If you are still confused, let me know, may be we can work this one more.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic