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

2022-08-31 20:31:16

类似问题:

我有一个对象,我想向库客户端(特别是脚本客户端)公开一个方法,如下所示:

interface MyNiceInterface
{
    public Baz doSomethingAndBlock(Foo fooArg, Bar barArg);
    public Future<Baz> doSomething(Foo fooArg, Bar barArg);
    // doSomethingAndBlock is the straightforward way;
    // doSomething has more control but deals with
    // a Future and that might be too much hassle for
    // scripting clients
}

但是我可用的原始“东西”是一组事件驱动的类:

interface BazComputationSink
{
    public void onBazResult(Baz result);
}

class ImplementingThing
{
    public void doSomethingAsync(Foo fooArg, Bar barArg, BazComputationSink sink);
}

其中EnprehensiingThing接受输入,做一些神秘的事情,比如在任务队列上排队,然后当结果发生时,在一个线程上被调用,该线程可能与ImportingThingThing.doSomethingAsync()调用的线程相同,也可能不同。sink.onBazResult()

有没有办法使用我拥有的事件驱动函数以及并发基元来实现MyNiceInterface,以便脚本客户端可以愉快地等待阻塞线程?

编辑:我可以使用FutureTask吗?


答案 1

使用您自己的未来实现:

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() 方法将立即返回并返回结果。


答案 2

好吧,有一个简单的解决方案,可以做这样的事情:

public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) {
  final AtomicReference<Baz> notifier = new AtomicReference();
  doSomethingAsync(fooArg, barArg, new BazComputationSink() {
    public void onBazResult(Baz result) {
      synchronized (notifier) {
        notifier.set(result);
        notifier.notify();
      }
    }
  });
  synchronized (notifier) {
    while (notifier.get() == null)
      notifier.wait();
  }
  return notifier.get();
}

当然,这假设您的结果永远不会为空...Baz


推荐