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

来源:互联网 发布:for数组去重 编辑:程序博客网 时间:2024/04/30 16:01

ListenableFuture类

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

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

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

?
executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(NUM_THREADS));//包装Executors创建的线程池
ListenableFuture<String> listenableFuture = executorService.submit(newCallable<String>()...);//获取ListableFuture对象
listenableFuture.addListener(newRunnable() {
      @Override
      publicvoidrun() {
          methodToRunOnFutureTaskCompletion();
      }
}, executorService);//注册回调函数

FutureCallback类

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

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

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

SettableFuture类:

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

?
SettableFuture<String> 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 implementsAsyncFunction<Long, String> {
    privateConcurrentMap<Long, String> map = Maps.newConcurrentMap();
    privateListeningExecutorService listeningExecutorService;
 
    @Override
    publicListenableFuture<String> apply(finalLong input)throwsException {
        if(map.containsKey(input)) {
            SettableFuture<String> listenableFuture = SettableFuture.create();//构建一个SettableFuture
            listenableFuture.set(map.get(input));
            returnlistenableFuture;
        }else{
            returnlisteningExecutorService.submit(newCallable<String>() {
                @Override
                publicString call()throwsException {
                    String retrieved =//compute to get the data;
                    map.putIfAbsent(input, retrieved);
                    returnretrieved;
                }
            });
        }
    }
}

FutureFallback类:

  • FutureFallback用于异常恢复的备份。
?
/**
 * 当Future任务失败后, 作为备份的Future
 */
public class FutureFallbackImpl implementsFutureFallback<String> {
    @Override
    publicListenableFuture<String> create(Throwable t)throwsException {
        if(tinstanceof FileNotFoundException) {
            SettableFuture<String> settableFuture = SettableFuture.create();
            settableFuture.set("Not Found");
            returnsettableFuture;
        }
        thrownewException(t);
    }
}

Futures类:

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

异步转换:

?
ListenableFuture<Person> lf = Futures.transform(ListenableFuture<String> f,AsyncFunction<String,Person> af);

使用FutureFallbacks:

?
1
ListenableFuture<String> lf = Futures.withFallback(ListenableFuture<String> f,FutureFallback<String> 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();
}

不吝指正。
0 0
原创粉丝点击