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

com.elypia.elypiai.restutils.RestLatch Maven / Gradle / Ivy

The newest version!
package com.elypia.elypiai.restutils;

import com.elypia.elypiai.restutils.impl.AbstractRestAction;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;

public class RestLatch extends AbstractRestAction> implements Iterable> {

    private final int TIMEOUT;
    private final boolean PARTIAL;

    private List> restActions;
    private boolean cancelled;

    public RestLatch() {
        this(4096);
    }

    public RestLatch(int timeout) {
        this(timeout, true);
    }

    public RestLatch(int timeout, boolean partial) {
        TIMEOUT = timeout;
        PARTIAL = partial;

        restActions = new ArrayList<>();
    }

    public void add(RestAction restAction) {
        restActions.add(restAction);
    }

    @Override
    public void queue(Consumer> success, Consumer ex) {
        if (restActions.isEmpty())
            throw new IllegalStateException("No requests added to latch prior to execution.");

        new Thread(() -> {
            List results = new ArrayList<>();
            CountDownLatch latch = new CountDownLatch(restActions.size());

            forEach((restAction) -> {
                restAction.queue((result) -> {
                    results.add(result);
                    latch.countDown();
                }, (e) -> {
                    if (!PARTIAL)
                        cancel();

                    latch.countDown();
                });
            });

            try {
                latch.await(TIMEOUT, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                cancel();

                if (!PARTIAL || results.isEmpty()) {
                    ex.accept(e);
                    return;
                }
            }

            success.accept(results);
        }).start();
    }

    @Override
    public List complete() throws IOException {
        throw new IllegalStateException();
    }

    @Override
    public void cancel() {
        if (!cancelled) {
            restActions.forEach(RestAction::cancel);
            cancelled = true;
        }
    }

    @Override
    public Iterator> iterator() {
        return restActions.iterator();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy