Flabbergasted101
Flabbergasted101

Reputation: 3

Java concurrency -_- visibility/reordering when sharing vars between threads

I'm taking my first steps into learning multithreading, and build a little test program in order to create some insight for myself. I'm not convinced my solution is safe because of the reordering possibility..

This is the main program:

public class SynchTest {

    private static Sychint i = new Sychint();
    private static SychBool b = new SychBool();

    public static void main(String[] args) {
        System.err.println("begin");
        b.setB(false);
        i.seti(100);

        // create 100 dra threads
        for (int i = 0; i < 1000; i++) {
            new dra().start();
        }

        // should these lines be synched as well in case of reordering? If so, how to?
        i.seti(200);
        b.setB(true);

    }

    private static class dra extends Thread {
        @Override
        public void run() {

            // wait for main thread to set b = true
            while (!b.getB()) {
                dra.yield();
            }

            // i should always be 200 in case of correct synchronisation
            if (i.geti() != 200) {
                System.err.println("oh noes! " + i.geti());
            } else {
                // System.out.println("synch working!");
            }

        }
    }

}

And these are the classes, Sychint:

public class Sychint {

    private int i = 0;

    public synchronized void seti(int i){
        this.i = i;
    }

    public synchronized int geti (){
        return this.i;
    }

}

SychBool:

public class SychBool {
    private boolean b;

    public synchronized boolean getB() {
        return b;
    }

    public synchronized void setB(boolean b) {
        this.b = b;
    }


}

Any advice/reassurance would be very helpfull!

Thnx,

newbie to multithreading :)

Upvotes: 0

Views: 94

Answers (1)

John Vint
John Vint

Reputation: 40256

// should these lines be synched as well in case of reordering? If so, how to?
i.seti(200);
b.setB(true);

In this case you are fine.

b.setB(true) cannot be reordered above i.seti(200). NormalStore and MonitorEnter cannot be ordered above MonitorExit. In your case the monitor exit happens at the end of seti, this is followed by a monitor enter and a normal store (of setB), so a reorder is not possible here.

Upvotes: 1

Related Questions