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

net.dongliu.prettypb.rpc.client.BlockingRpcCallback Maven / Gradle / Ivy

There is a newer version: 0.3.5
Show newest version
package net.dongliu.prettypb.rpc.client;

import net.dongliu.prettypb.runtime.include.RpcCallback;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * convert async call to syn
 */
public class BlockingRpcCallback implements RpcCallback {

    /**
     * the rpc call result
     */
    private Object value;
    /**
     * the error msg
     */
    private Exception exception;
    private CountDownLatch countDownLatch;

    public BlockingRpcCallback() {
        countDownLatch = new CountDownLatch(1);
    }

    @Override
    public void onFinished(Object value) {
        this.value = value;
        countDownLatch.countDown();
    }

    @Override
    public void onError(Exception e) {
        this.value = null;
        this.exception = e;
        countDownLatch.countDown();
    }

    /**
     * get rpc call result
     *
     * @return
     */
    public Object getValue() {
        return value;
    }

    public Exception getException() {
        return exception;
    }

    /**
     * await the rpc call finished
     *
     * @param timeout timeout in milliseconds
     * @throws InterruptedException TimeoutException
     */
    public void await(int timeout) throws InterruptedException, TimeoutException {
        if (!countDownLatch.await(timeout, TimeUnit.MILLISECONDS)) {
            throw new TimeoutException();
        }
    }
}