Asynchronous event dispatch in Java

I am porting a C # program in Java that makes extensive use of delegates and the delegate method BeginInvokefor asynchronous event notification. Take, for example, the data stream. It may need to notify yet another worker thread of its state, as well as the GUI.

It seems to me that the best way to notify of various events for different classes is to have an interface IClassNameHereWatcherthat defines all types of events that the event "publish" class will have to notify, and that each class that must listen will implement this interface and register as a listener . That I'm not quite sure how to make this asynchronous. Here are some of what I mean:

public interface IFrobWatcher {
    void frobDidSomething();
    void frobReceivedData(object data);
}

public class Frob implements Runnable {
    List<IFrobWatcher> watchers = new ArrayList<IFrobWatcher>();

    private void run() {
        while (true) {
            // Long running task
            if (blah) notifyWeDidSomething();
            notifyOfData(someDataObject);
        }
    }

    public void addWatcher(IFrobWatcher watcher) {
        watchers.Add(watcher);
    }

    private void notifyWeDidSomething() {
        for (IFrobWatcher watcher : watchers) {
            watcher.frobDidSomething(); // How do I make this asynchronous?
        }
    }

    private void notifyOfData(object someDataObject) {
        for (IFrobWatcher watcher : watchers) {
            watcher.frobReceivedData(someDataObject); // How do I make this asynchronous?
        }
    }

}

public class FrobWatcher implements IFrobWatcher {
    private Frob frobToWatch;

    public FrobWatcher(Frob frob) {
        frobToWatch = frob;
        frobToWatch.addListener(this);
    }

    public void FrobDidSomething() {
        System.out.println("Frob did something!");
    }

    public void FrobReceivedData(object received) {
        System.out.println("Frob received: " + received.ToString());
    }

    public static void main(string[] args) {
        Frob f = new Frob();
        FrobWatcher fw = new FrobWatcher(f);
        (new Thread(f)).start();
    }
}

, , , , . - , , .

+3
1

Executor java.util.concurrent. , Raptor framework:

scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(
    filesPoller, 0 /*initial delay*/,
    checkInterval,
    TimeUnit.MILLISECONDS
);

NB. .

+2

Source: https://habr.com/ru/post/1729451/


All Articles