Q:

Listener to notify the completion of a series of events(starting simultaneous services)

I have three classes from which I start three services. These three services will be started simultaneously.
I have callback methods in each of these service class to know whether that particular service has been started.
There is no order in which what service out of these three would get started first, though they are started simultaneously.
Can someone please let me know the best approach to use in order that I am notified at the start of last service?
Any help is appreciated.

A:

I would do it as follows:
public class CounterAndNotifier
{
    private int counter = 0;
    private int count;
    private Runnable runnable;

    public CounterAndNotifier(int count, Runnable runnable)
    {
        this.count = count;
        this.runnable = runnable;
    }

    public synchronized void incrementCounter()
    {
        counter++;
        if (counter == count) {
            runnable.run();
        }
    }
}

Create a class that takes a Runnable which should be notified once all the three services start.
This class maintains a counter and a synchronized method to increment the counter.
The method to increment the counter will call the Runnable.run() once the count reaches 3.
Create an object of this class and pass it to the three services to call the incrementCounter() method once the service is complete up and running.

Hope this helps.

