I am writing a GUI for a program which allows a user to accept or decline a request send to a listening server socket. I do this by using a DoYouAcceptWindow
and another bit of code which opens it.
The code in DoYouAcceptWindow.java
is as follows
public class DoYouAcceptWindow extends JFrame implements MouseListener{
private short d = 0;
private JButton accept;
public DoYouAcceptWindow() {
setLayout(new FlowLayout());
accept = new JButton("Accept");
accept.addMouseListener(this);
add(accept);
pack();
setVisible(true);
}
public short getDecided() {
return d;
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(accept)) {
System.out.println("Accepted");
d = 2;
}
}
}
(I have remove a lot of unnecessary functions from this as well as the ability to decline the request just to make it easier to read)
And the code that uses the above class:
while (true) {
DoYouAcceptWindow w = new DoYouAcceptWindow();
short decided = w.getDecided();
while (decided == 0) {
decided = w.getDecided();
}
System.out.println("Done!");
w.dispose();
if (w.getDecided() == 2) {
break;
}
}
(This code has also had a lot of unnecessary parts removed)
When you press the button, it prints "accepted" like it should (and I assume it sets d = 1 or 2). However, it does not break out of the while loop. When I add a print statement into the while loop however (like this):
while (decided == 0) {
decided = w.getDecided();
System.out.println(0);
}
It fixes itself. If I run it in debug mode (in eclipse), it fixes itself. Why does it not break out of the while loop without the print statement? And how can I fix it? (without adding a print statement)
Can't say for sure, but with the description this could be a memory visibility issue.
Could you try declaring the value volatile?
private volatile short d = 0;