deathiop
deathiop

Reputation: 23

Kind of a Rendez-Vous in Java which does not work

I have some troubles using wait() and notify(). I need to have a kind of rendez-vous.

Here is the thing, in a small piece of code:

class A {
    private Rdv r;

    public A(Rdv r) {
        this.r = r;
    }

    public void someMethod() {
        synchronized(r) {
            r.wait();
        }

        // ***** some stuff never reached*****
    }
}

class Rdv { 
    private int added;
    private int limit;

    public Rdv(int limit) {
        this.added = 0;
        this.limit = limit;
    }

    public void add() {
        this.added++;

        if(this.added == this.limit) {
            synchronized(this) {
                this.notifyAll();
            }
        }
    }
}

class Main {
    public static void main(String[] args) {
        Rdv rdv = new Rdv(4);

        new Runnable() {
            public void run() {
                A a = new A(rdv);
                a.someMethod();
            }
        }.run();

        rdv.add();
        rdv.add();
        rdv.add();
        rdv.add();
    }
}

The idea is to wait until 4 threads tell "hey, i'm done" before to run the end of someMethod(). But the wait() lasts forever, despite of the notifyAll().

I don't get how

Upvotes: 2

Views: 1815

Answers (4)

Tudor
Tudor

Reputation: 62459

Um... am I the only one noticing that you are not actually starting any threads?

    new Runnable() {
        public void run() {
            A a = new A(rdv);
            a.someMethod();
        }
    }.run();

should be

 Thread t = new Thread(
    new Runnable() {
        public void run() {
            A a = new A(rdv);
            a.someMethod();
        }
    });
 t.start();

And this should be executed 4 times if you want to have 4 threads waiting.

Upvotes: 3

Michael Borgwardt
Michael Borgwardt

Reputation: 346407

Instead of messing with wait() and notify() yourself, consider using a CountDownLatch

Upvotes: 2

Adel Boutros
Adel Boutros

Reputation: 10285

Of course it won't be reached, because every instance of class A has a different instance of class Rdv;

You need to use RDV as a static variable in class A

Upvotes: 1

Mark Peters
Mark Peters

Reputation: 81114

wait() and notify() are not meant to be used directly but rather are primitives that better libraries use for low-level synchronization.

You should use a higher-level concurrency mechanism, such as CountDownLatch. You would want to use a CountDownLatch with a value of 4. Have each of the threads call the countDown() method of the latch, and the one you want to wait to call await().

private CountDownLatch rendezvousPoint = new CountDownLatch(4);

//wait for threads
rendezvousPoint.await();

//do stuff after rendezvous

//in the other 4 threads:
rendezvousPoint.countDown();

Upvotes: 6

Related Questions