Java - volatile variable is not updating

2019-09-20 17:17发布

I'm working on an interactive sorting application in JavaFx:

  • The numbers are represented by rectangles
  • Every time two numbers are swapped the rectangles are swapped(using timeline - animation)

This is one of the sorting algorithms:

 public class BubbleSort implements SortAlgorithm {
private volatile Boolean swaping;

public void sort(double[] array, CompareFunction compareFunction, Model model, Controller controller) {
    Boolean ord;
    int i;
    double aux;

    swaping = false;

    do {
        ord = true;

        for (i = 0; i < array.length - 1; i++) {
            if (compareFunction.compare(array[i], array[i + 1]) == false) {
                while (swaping);

                swaping = true;

                aux = array[i];
                array[i] = array[i + 1];
                array[i + 1] = aux;
                ord = false;

                controller.swapRectangles(model.getRectangles().get(i), model.getRectangles().get(i + 1), this);
            }
        }
    } while (ord == false);
}

public void setSwaping(Boolean swaping) {
    this.swaping = swaping;
}

}

This is the prototype of the swapRectangles method:

public void swapRectangles(final Rectangle rectangle1, final Rectangle rectangle2,    final BubbleSort bubbleSort)

And when timeline ends I udpate "swaping" value:

        timeline2.setOnFinished(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            setRectangleFill(rectangle2, Color.BLACK);
            rectangle2.setX(rectangle1X);
            bubbleSort.setSwaping(false);
        }
    });

The problem is that the "swaping" variable is never updating(the setSwaping method is never called).

Do you know why?

2条回答
走好不送
2楼-- · 2019-09-20 17:49

I think you update swaping = true in setSwaping method but in sort method you again set swaping= false before while loop execute. So I think your while loop is never executing since swaping is false. So you assuming that value is not being updating.

Remove this line from your sort method:

swaping = false;


while (swaping);

remove ; and put your code inside while block.

查看更多
Animai°情兽
3楼-- · 2019-09-20 18:02
  1. Running while(swaping); puts a hard pressure on processor, you are taking all it's power and give it to "do-nothing" loop. To solve that either add sleep inside: while(swaping) Thread.sleep(100); or use more convenient synchronization mechanism like Semaphore

  2. Also if you run sort on UI thread you block it entirely, thus setOnFinished will never get a chance to be run. You should run sort on a separate thread:

    new Thread() {
        public void run() {
            new BubbleSort().sort(array, compareFunction, model, controller);
        }
    }.start();
    

If you update UI from this thread, make sure you wrap UI calls into Platform.runLater.

查看更多
登录 后发表回答