How to use the Guava ListenableFuture and the Futures.chain() methods

谁说我不能喝 提交于 2019-12-19 09:57:50

问题


I have a homework task that requires me to learn how to use the Guava concurrency library.

In the task I have several thread pools, where each one is controlled by an individual object.

Each pool has several working threads that perform simple tasks (mostly emulating doing stuff by using Thread.sleep(long)) and all those simple tasks are stored in a container object that emulates a messageboard.

Each simple task has a dependency list of other tasks, and it cannot be executed until all of those tasks are completed.

How can I benefit from the Guava library using the ListenableFuture and the Futures.chain()?

I have searched everywhere for some extensive example code online, but didn't find anything that I understand how to use.


回答1:


As Louis mentions, I think that Futures.allAsList etc. could be useful for you. However, I think that Futures.chain does seem useful and appropriate for the situation you describe. Since this is an assignment meant to challenge you, I'm not going to say any more than this: Futures.chain allows you to submit a task for execution upon completion of another task, and it returns a new ListenableFuture representing the result of that task. How does that apply to what you're trying to do?




回答2:


You might be interested in reading the presentation slides on Guava util.concurrent, linked on the Guava homepage (slide 11 and onward). They really helped me crystallize my understanding of ListenableFuture and why it's so useful.

My guess is that the goal of your assignment is to understand how Futures work, and how Guava's ListenableFuture and Futures.chain() simplifies their use when coordinating multiple tasks.

The only open source code that comes to mind that uses ListenableFuture is sitebricks-mail:

  • MailClient interface
  • NettyImapClient implementation

I don't know if it uses Futures.chain(), though.




回答3:


I don't think Futures.chain() is the answer here, if the primary issue is dealing with task dependency lists. More likely is Futures.allAsList or Futures.successfulAsList, which take multiple futures, and return a future that returns only after all of the input futures have succeeded or failed.



来源:https://stackoverflow.com/questions/8626033/how-to-use-the-guava-listenablefuture-and-the-futures-chain-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!