Guava并发(2)——ListenableFuture\FutureCallback\SettableFuture\Futures

ListenableFuture类

  • jdk5之后有了Future这种异步执行的结构
ExecutorService executor = Executors.newCachedThreadPool();
   Future future = executor.submit(new Callable(){
                                public Integer call() throws Exception{
                                   return service.getCount();
} });
//Retrieve the value of computation
Integer count = future.get();

  • ListenableFuture对Future进行了扩展,允许注册一个回调函数,task执行完后自动调用。
  • 获取ListableFuture对象。

正如我们获取Future对象要通过ExecutorService.submit(Callable)来获取一样,我们可以这样创建ListenableFuture对象:

?
executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(NUM_THREADS)); //包装Executors创建的线程池
ListenableFuture listenableFuture = executorService.submit( new Callable()...); //获取ListableFuture对象
listenableFuture.addListener( new Runnable() {
       @Override
       public void run() {
           methodToRunOnFutureTaskCompletion();
       }
}, executorService); //注册回调函数

FutureCallback类

  • FutureCallback定义了onSuccessonFailure方法,onSuccess方法会接收一个Future对象,这样我们就可以获取Future的结果。
  • 首先需要一个FutureCallback实现类。
?
/**
  * 定义一个FutureCallBack实现类
  */
public class FutureCallbackImpl implements FutureCallback {
     private StringBuilder builder = new StringBuilder();
 
     @Override
     public void onSuccess(String result) {
         builder.append(result).append( " successfully" );
     }
 
     @Override
     public void onFailure(Throwable t) {
         builder.append(t.toString());
     }
 
     public String getCallbackResult() {
         return builder.toString();
     }
}

使用实例:
?
ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
ListenableFuture futureTask = executorService.submit( new Callable() { //创建ListenaleFuture对象
                     @Override
                     public String call() throws Exception {
                         return "Task completed" ;
                     }
                 });
FutureCallbackImpl callback = new FutureCallbackImpl();
Futures.addCallback(futureTask, callback); //添加回调
callback.getCallbackResult(); //获取结果

如果CallBack是一个耗时操作,你应该选择另一个注册CallBack:
?
Futures.addCallback(futureTask,callback,executorService); //提供另一个线程池来执行性回调

SettableFuture类:

SettableFuture可以用来设置要返回得值:

?
SettableFuture sf = SettableFuture.create();
//Set a value to return
sf.set( "Success" );
//Or set a failure Exception
sf.setException(someException);

AsyncFunction:

  • 该接口与函数式编程密切相关, 类似Function, 但apply方法会转换成一个ListenableFuture封装的范型对象。
?
public class AsyncFuntionSample implements AsyncFunction {
     private ConcurrentMap map = Maps.newConcurrentMap();
     private ListeningExecutorService listeningExecutorService;
 
     @Override
     public ListenableFuture apply( final Long input) throws Exception {
         if (map.containsKey(input)) {
             SettableFuture listenableFuture = SettableFuture.create(); //构建一个SettableFuture
             listenableFuture.set(map.get(input));
             return listenableFuture;
         } else {
             return listeningExecutorService.submit( new Callable() {
                 @Override
                 public String call() throws Exception {
                     String retrieved = //compute to get the data;
                     map.putIfAbsent(input, retrieved);
                     return retrieved;
                 }
             });
         }
     }
}

FutureFallback类:

  • FutureFallback用于异常恢复的备份。
?
/**
  * 当Future任务失败后, 作为备份的Future
  */
public class FutureFallbackImpl implements FutureFallback {
     @Override
     public ListenableFuture create(Throwable t) throws Exception {
         if (t instanceof FileNotFoundException) {
             SettableFuture settableFuture = SettableFuture.create();
             settableFuture.set( "Not Found" );
             return settableFuture;
         }
         throw new Exception(t);
     }
}

Futures类:

  • Futures类是有关Future实例的一个工具类。

异步转换:

?
ListenableFuture lf = Futures.transform(ListenableFuture f,AsyncFunction af);

使用FutureFallbacks:

?
1
ListenableFuture lf = Futures.withFallback(ListenableFuture f,FutureFallback fb);

RateLimiter:

  • RateLimiter限制访问每秒访问资源的线程数。有点类似信号量Semaphore。
?
RateLimiter limiter = RateLimiter.create( 4.0 ); //每秒不超过4个任务被提交

?
limiter.acquire();  //请求RateLimiter, 超过permits会被阻塞
executor.submit(runnable); //提交任务

也有非阻塞式地尝试:
?
If(limiter.tryAcquire()){ //未请求到limiter则立即返回false
     doSomething();
} else {
     doSomethingElse();
}

不吝指正。

你可能感兴趣的:(guava,JAVA并发包)