0

I am trying Peterson's Solution for the Critical Section Problem, and I noticed that my static variable doesn't update unless I add a System.out.print(""); statement.

Why is this so?

Thanks.

The code for Peterson.java is below:

public class Peterson {
    public static void main(String[] args) throws InterruptedException {
        Process p1 = new Process(0);
        Process p2 = new Process(1);
        p1.start();
        p2.start();
        p1.join();
        p2.join();
    }
}

class Process extends Thread {
    static int turn;
    static boolean[] wait = new boolean[2];

    int ind;
    public Process(int ind) {
        this.ind = ind;
    }

    @Override
    public void run() {
        int ind2 = 1-ind;
        wait[ind] = true;
        turn = ind2;
        
        // USING THIS WORKS
        // while(wait[ind2] && turn == ind2) {System.out.print("");}
        // USING THIS DOESN'T WORK
        while(wait[ind2] && turn == ind2) {;}

        // Critical Section
        System.out.printf("%d Started%n", ind);
        for (long t = System.currentTimeMillis(); System.currentTimeMillis() - t < 100;);
        System.out.printf("%d Ended%n", ind);

        wait[ind] = false;
    }
}
John
  • 106
  • 7
  • 1
    `static volatile int turn;` – DuncG Jun 19 '23 at 19:39
  • Wow, That was all that it took :) – John Jun 19 '23 at 19:46
  • Is there any chance you know what is `transient`? – John Jun 19 '23 at 19:50
  • 1
    transient: [JLS 8.3.1.3. transient Fields](https://docs.oracle.com/javase/specs/jls/se20/html/jls-8.html#jls-8.3.1.3): "*Variables may be marked transient to indicate that they are not part of the persistent state of an object.*" and for example used in [`ObjectOutputStream`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/io/ObjectOutputStream.html): "*The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.*" – user16320675 Jun 19 '23 at 21:06
  • 1
    and maybe this question: [Why does Java have transient fields?](https://stackoverflow.com/questions/910374/why-does-java-have-transient-fields) – user16320675 Jun 19 '23 at 21:09

0 Answers0