在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java那点事——异步

2017-2-7 13:38| 发布者: zhangjf| 查看: 441| 评论: 0

摘要: 在JDK1.6提供了Future,FutureTask,ExecutorService等用于支持异步编程,但是Future,FutureTask没有提供callback机制,只能主动轮询,通过get去获取结果。 Guava的ListenableFuture对此做了扩展,支持callback机 ...

在JDK1.6提供了Future,FutureTask,ExecutorService等用于支持异步编程,但是Future,FutureTask没有提供callback机制,只能主动轮询,通过get去获取结果。

Guava的ListenableFuture对此做了扩展,支持callback机制。

就callback机制的扩展而言,也并不复杂。看看ListenableFuture与ListenableFutureTask:

  1. public interface ListenableFuture extends Future {
  2. void addListener(Runnable listener, Executor executor);
  3. }
  4. public class ListenableFutureTask extends FutureTask implements ListenableFuture {
  5. // The execution list to hold our listeners.
  6. private final ExecutionList executionList = new ExecutionList();
  7. //………
  8. @Override
  9. public void addListener(Runnable listener, Executor exec) {
  10. executionList.add(listener, exec);
  11. }
  12. /**
  13. * Internal implementation detail used to invoke the listeners.
  14. */
  15. @Override
  16. protected void done() {
  17. executionList.execute();
  18. }
  19. }
复制代码

callback通过addListener添加,通过override FutureTask的done()函数实现回调。 查看FutureTask会在Task执行完以后调用done()函数,如:

  1. /**
  2. * Removes and signals all waiting threads, invokes done(), and
  3. * nulls out callable.
  4. */
  5. private void finishCompletion() {
  6. // assert state > COMPLETING;
  7. for (WaitNode q; (q = waiters) != null;) {
  8. if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
  9. for (;;) {
  10. Thread t = q.thread;
  11. if (t != null) {
  12. q.thread = null;
  13. LockSupport.unpark(t);
  14. }
  15. WaitNode next = q.next;
  16. if (next == null)
  17. break;
  18. q.next = null; // unlink to help gc
  19. q = next;
  20. }
  21. break;
  22. }
  23. }
  24. done();
  25. callable = null; // to reduce footprint
  26. }
复制代码

与JDK一样,ListenableFuture需要通过ExecutorService创建,Guava定义了对应的ExecutorService,并提供MoreExecutors作为工具类,其中实现了ListeningDecorator与ScheduledListeningDecorator,它们都是对应的JDK ExecutorService的装饰。MoreExecutors提供的工具api非常很多,需要细细瞧瞧。

1.8版本开始,JDK也开始提供了一些更好支持异步编程的Future,典型的有CompletableFuture.

如果未说明,本Blog中文章皆为原创文章,请尊重他人劳动,转载请注明:转载自jmatrix

本文链接地址: Java那点事——异步

(注:一般引用了,我都会添加引用,如果有侵权的请联系我)

来自: http://www.jmatrix.org/java/1102.html

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 00:26

Copyright 2015-2025 djqfx

返回顶部