All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.notifier.dispatchers.BlockingDispatcher Maven / Gradle / Ivy

There is a newer version: 1.3.0
Show newest version
package com.notifier.dispatchers;

import com.notifier.Event;
import com.notifier.Listener;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Predicate;

public class BlockingDispatcher implements EventDispatcher {

    private final ExecutorService mExecutorService;
    private final long mMaxWaitTime;
    private final TimeUnit mWaitTimeUnit;

    public BlockingDispatcher(ExecutorService executorService, long maxWaitTime, TimeUnit waitTimeUnit) {
        mExecutorService = executorService;
        mMaxWaitTime = maxWaitTime;
        mWaitTimeUnit = waitTimeUnit;
    }

    @Override
    public void dispatch(Collection listeners, Predicate listenerFilter, Event event, BiConsumer listenerCall) {
        Collection futures = new ArrayList<>();

        for (Listener listener : listeners) {
            if (listenerFilter.test(listener)) {
                Future future = mExecutorService.submit(new DispatchingTask(listener, event, listenerCall));
                futures.add(future);
            }
        }

        for (Future future : futures) {
            try {
                if (mMaxWaitTime <= 0) {
                    future.get();
                } else {
                    future.get(mMaxWaitTime, mWaitTimeUnit);
                }
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                // ignore
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy