Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain this problem from k&b

 
Stefan Koev
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question from the k&b practice exams book and has me confused. The correct answers are ABC according to the answer key. I understand those, but to me, D also seems a valid answer. The book says that D is incorrect because the value of id swaps between 0 and 1, and there is no chance for the same method to be executed twice.
But what if one thread modifies id, and the other thread stills sees the old value of id because id is not volatile? Then both threads could call the pick method, one after the other. Please advise.

public class Stone implements Runnable {
static int id = 1;
public void run() {
try {
id = 1 - id;
if(id == 0) { pick(); } else { release(); }
} catch(Exception e) { }
}
private static synchronized void pick() throws Exception {
System.out.print("P ");
System.out.print("Q ");
}
private synchronized void release() throws Exception {
System.out.print("R ");
System.out.print("S ");
}
public static void main(String[] args) {
Stone st = new Stone();
new Thread(st).start();
new Thread(st).start();
} }


Which are true? (Choose all that apply.)
A. The output could be P Q R S
B. The output could be P R S Q
C. The output could be P R Q S
D. The output could be P Q P Q
E. The program could cause a deadlock.
F. Compilation fails.
 
nitin sethi
Ranch Hand
Posts: 59
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stefan Koev wrote:But what if one thread modifies id, and the other thread stills sees the old value of id because id is not volatile? Then both threads could call the pick method, one after the other. Please advise.


The variable id is static. So, the two threads would read the present value irrespective of which one changes it. The below link would be a good read for you.

http://www.coderanch.com/t/382150/java/java/volatile-static-keywords

-- Nitin
 
dennis deems
Ranch Hand
Posts: 808
 
Stefan Koev
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Great discussion, thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic