将异步计算包装为同步(阻塞)计算

将异步计算包装为同步(阻塞)计算,第1张

将异步计算包装为同步(阻塞)计算

使用您自己的Future实现:

public class BazComputationFuture implements Future<Baz>, BazComputationSink {    private volatile Baz result = null;    private volatile boolean cancelled = false;    private final CountDownLatch countDownLatch;    public BazComputationFuture() {        countDownLatch = new CountDownLatch(1);    }    @Override    public boolean cancel(final boolean mayInterruptIfRunning) {        if (isDone()) { return false;        } else { countDownLatch.countDown(); cancelled = true; return !isDone();        }    }    @Override    public Baz get() throws InterruptedException, ExecutionException {        countDownLatch.await();        return result;    }    @Override    public Baz get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {        countDownLatch.await(timeout, unit);        return result;    }    @Override    public boolean isCancelled() {        return cancelled;    }    @Override    public boolean isDone() {        return countDownLatch.getCount() == 0;    }    public void onBazResult(final Baz result) {        this.result = result;        countDownLatch.countDown();    }}public Future<Baz> doSomething(Foo fooArg, Bar barArg) {    BazComputationFuture future = new BazComputationFuture();    doSomethingAsync(fooArg, barArg, future);    return future;}public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) {    return doSomething(fooArg, barArg).get();}

该解决方案在内部创建一个CountDownLatch,一旦收到回调,该计数器将被清除。如果用户调用get,则使用CountDownLatch阻止调用线程,直到计算完成并调用onBazResult回调。CountDownLatch将确保如果回调在调用get()之前发生,则get()方法将立即返回结果。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5103961.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存