缠绕的一系列异步调用与返回值的同步方法 [英] Wrapping a series of asynchronous calls with a synchronous method with a return value

查看:242
本文介绍了缠绕的一系列异步调用与返回值的同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的code使用,在达到高潮的结果异步进程的系列。我需要包装每个这些在于,每个由与结果作为返回值的同步方法来访问这样的方式。我想使用执行程序的服务,这样做,以便允许许多这些在同一时间发生。我有一个未来的可能是相关的我的实现的感觉,但我不能想出一个好办法做到这一点。

My current code uses series of asynchronous processes that culminate in results. I need to wrap each of these in such a way that each is accessed by a synchronous method with the result as a return value. I want to use executor services to do this, so as to allow many of these to happen at the same time. I have the feeling that Future might be pertinent to my implementation, but I can't figure out a good way to make this happen.

我现在有什么:

public class DoAJob {
  ResultObject result;

  public void stepOne() {
    // Passes self in for a callback
    otherComponent.doStepOne(this);
  }

  // Called back by otherComponent once it has completed doStepOne
  public void stepTwo(IntermediateData d) {
    otherComponent.doStepTwo(this, d);
  }

  // Called back by otherComponent once it has completed doStepTwo
  public void stepThree(ResultObject resultFromOtherComponent) {
    result = resultFromOtherComponent;
  //Done with process
  }
}

这工作pretty以及内部,但现在我需要我的过程映射到一个同步方法像一个返回值:

This has worked pretty well internally, but now I need to map my process into a synchronous method with a return value like:

public ResultObject getResult(){
  // ??? What goes here ???
}

有没有人对如何实现这个好主意优雅?

Does anyone have a good idea about how to implement this elegantly?

推荐答案

如果您想打开一个异步操作(这在完成时执行的回调),进入一个同步/阻断一个,你可以使用一个阻塞队列。如果你愿意,你可以在将来的对象包装这个了。

If you want to turn an asynchronous operation (which executes a callback when finished), into a synchronous/blocking one, you can use a blocking queue. You can wrap this up in a Future object if you wish.


  1. 定义它可以容纳一个阻塞队列,只有一个元素:

  1. Define a blocking queue which can hold just one element:

的BlockingQueue<结果>的BlockingQueue =新ArrayBlockingQueue<结果>(1);

启动异步进程(将在后台运行),并写回调,这样当它完成,它增加了它的结果,以阻塞队列。

Start your asynchronous process (will run in the background), and write the callback such that when it's done, it adds its result to the blocking queue.

在您的前景/应用程序线程,它已经采取()从队列中,而阻塞,直到元素变得可用:

In your foreground/application thread, have it take() from the queue, which blocks until an element becomes available:

结果结果= blockingQueue.take();

我写的(前台线程需要阻止从远程计算机的异步响应)使用类似的Future以前类似的东西,你可以找到例如code <一个href=\"http://$c$c.google.com/p/mobility-rpc/source/browse/mobility-rpc/trunk/src/main/java/com/google$c$c/mobilityrpc/session/impl/MobilitySessionImpl.java#395\"相对=nofollow>这里。

I wrote something similar before (foreground thread needs to block for an asynchronous response from a remote machine) using something like a Future, you can find example code here.

这篇关于缠绕的一系列异步调用与返回值的同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆