首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将异步计算包装为同步(阻塞)计算

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

Stack Overflow用户
提问于 2010-02-01 22:05:59
回答 7查看 30K关注 0票数 51

类似的问题:

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

代码语言:javascript
复制
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
}

但是,我拥有的原始“东西”是一组事件驱动的类:

代码语言:javascript
复制
interface BazComputationSink
{
    public void onBazResult(Baz result);
}

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

在ImplementingThing接受输入的情况下,执行一些神秘的操作,比如在任务队列上排队,然后当结果发生时,调用一个线程,该线程可能与调用ImplementingThing.doSomethingAsync()的线程相同,也可能不是同一个线程。

有什么方法可以使用我拥有的事件驱动函数以及并发原语来实现MyNiceInterface,这样脚本客户机就可以愉快地等待阻塞线程了吗?

编辑:--我能用FutureTask吗?

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2010-02-01 22:26:13

使用您自己的未来实现:

代码语言:javascript
复制
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()方法将立即返回并得到一个结果。

票数 48
EN

Stack Overflow用户

发布于 2010-02-01 22:22:50

嗯,有一个简单的解决方案是这样做的:

代码语言:javascript
复制
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结果永远不会为空…。

票数 17
EN

Stack Overflow用户

发布于 2012-09-21 13:27:14

google 番石榴图书馆有一个易于使用的SettableFuture,使得这个问题非常简单(大约10行代码)。

代码语言:javascript
复制
public class ImplementingThing {

public Baz doSomethingAndBlock(Foo fooArg, Bar barArg) {
    try {
        return doSomething(fooArg, barArg).get();
    } catch (Exception e) {
        throw new RuntimeException("Oh dear");
    }
};

public Future<Baz> doSomething(Foo fooArg, Bar barArg) {
    final SettableFuture<Baz> future = new SettableFuture<Baz>();
    doSomethingAsync(fooArg, barArg, new BazComputationSink() {
        @Override
        public void onBazResult(Baz result) {
            future.set(result);
        }
    });
    return future;
};

// Everything below here is just mock stuff to make the example work,
// so you can copy it into your IDE and see it run.

public static class Baz {}
public static class Foo {}
public static class Bar {}

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

public void doSomethingAsync(Foo fooArg, Bar barArg, final BazComputationSink sink) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Baz baz = new Baz();
            sink.onBazResult(baz);
        }
    }).start();
};

public static void main(String[] args) {
    System.err.println("Starting Main");
    System.err.println((new ImplementingThing()).doSomethingAndBlock(null, null));
    System.err.println("Ending Main");
}
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2180419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档