While loop bug? Stuck on empty

Only for extreme tight loops like while (!nextMove) { }, w/o anything to it, would cause JIT to never check whether the non-volatile field nextMove had changed its value.

For any healthy regular loops, JIT will eventually check non-volatile fields, and break outta the loop!

If it wasn’t so, the whole Java ecosystem would crumble in an instant due to your non-volatile fields doomsday multi-threading scenario!

We can confidently use a loop to await for any non-volatile field to be changed from another Thread!

Here’s a practical example, which awaits for Capture::width to have non-zero value in a while () loop under the sketch’s own “Animation” Thread:

/**
 * Efficient WebCam Capture (2.0.1)
 * GoToLoop (2016-May-05)
 *
 * Forum.Processing.org/two/discussion/16435/
 * how-to-make-the-webcam-capture-window-go-away-or-put-images-over-it
 *
 * GitHub.com/processing/processing-video/pull/30
 */

import processing.video.Capture;
Capture cam;

static final String RENDERER = JAVA2D;
//static final String RENDERER = FX2D;

static final int CAM = 1, FPS_ADJUST = 5, DELAY = 5;

void setup() {
  size(640, 480, RENDERER);
  initFeed();

  float canvasFPS = cam.frameRate + FPS_ADJUST;
  frameRate(canvasFPS);

  println("Cam's FPS:", cam.frameRate, "\t\tCanvas's FPS:", canvasFPS);
  print("Cam's size:", cam.width, 'x', cam.height, '\t');
  println("Canvas's size:", width, 'x', height);
}

void draw() {
  background(cam);
  getSurface().setTitle( str(round(frameRate)) );
}

void captureEvent(final Capture c) {
  c.read();
}

void initFeed() {
  String[] cams = Capture.list();
  printArray(cams);
  println("\nChosen Cam #" + CAM + ':', cams[CAM]);

  ( cam = new Capture(this, cams[CAM]) ).start();

  println("cam.width: " + cam.width); // cam.width: 0
  while (cam.width == 0)  delay(DELAY);
  println("cam.width: " + cam.width); // cam.width: 640

  if (cam.width > 0)  getSurface().setSize(cam.width, cam.height);
}

Pay attention to this particular code block:

println("cam.width: " + cam.width); // cam.width: 0
while (cam.width == 0)  delay(DELAY);
println("cam.width: " + cam.width); // cam.width: 640

Before while (cam.width == 0) delay(DELAY); starts, println() is used to log the current value of Capture::width non-volatile field, which is still 0.

Of course that loop, which is run by the “Animation” Thread btW, expects Capture’s own Thread to change its non-volatile field width.

Even though the “Animation” Thread coulda cached the non-volatile field Capture::width, it will eventually check whether the real Capture::width has changed its value.

According to your scenario, the “Animation” Thread would never be aware of the changes made to Capture::width by Capture’s own Thread!