Guava并发(2)——ListenableFuture\FutureCallback\SettableFuture\Futures
来源:互联网 发布:for数组去重 编辑:程序博客网 时间:2024/04/30 16:01
ListenableFuture类
- jdk5之后有了Future这种异步执行的结构
- ListenableFuture对Future进行了扩展,允许注册一个回调函数,task执行完后自动调用。
- 获取ListableFuture对象。
正如我们获取Future对象要通过ExecutorService.submit(Callable)来获取一样,我们可以这样创建ListenableFuture对象:
executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(NUM_THREADS));
//包装Executors创建的线程池
ListenableFuture<String> listenableFuture = executorService.submit(
new
Callable<String>()...);
//获取ListableFuture对象
listenableFuture.addListener(
new
Runnable() {
@Override
public
void
run() {
methodToRunOnFutureTaskCompletion();
}
}, executorService);
//注册回调函数
FutureCallback类
- FutureCallback定义了onSuccess和onFailure方法,onSuccess方法会接收一个Future对象,这样我们就可以获取Future的结果。
- 首先需要一个FutureCallback实现类。
/**
* 定义一个FutureCallBack实现类
*/
public
class
FutureCallbackImpl
implements
FutureCallback<String> {
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<String> futureTask = executorService.submit(
new
Callable<String>() {
//创建ListenaleFuture对象
@Override
public
String call()
throws
Exception {
return
"Task completed"
;
}
});
FutureCallbackImpl callback =
new
FutureCallbackImpl();
Futures.addCallback(futureTask, callback);
//添加回调
callback.getCallbackResult();
//获取结果
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
implements
AsyncFunction<Long, String> {
private
ConcurrentMap<Long, String> map = Maps.newConcurrentMap();
private
ListeningExecutorService listeningExecutorService;
@Override
public
ListenableFuture<String> apply(
final
Long input)
throws
Exception {
if
(map.containsKey(input)) {
SettableFuture<String> listenableFuture = SettableFuture.create();
//构建一个SettableFuture
listenableFuture.set(map.get(input));
return
listenableFuture;
}
else
{
return
listeningExecutorService.submit(
new
Callable<String>() {
@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<String> {
@Override
public
ListenableFuture<String> create(Throwable t)
throws
Exception {
if
(t
instanceof
FileNotFoundException) {
SettableFuture<String> settableFuture = SettableFuture.create();
settableFuture.set(
"Not Found"
);
return
settableFuture;
}
throw
new
Exception(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
- Guava并发(2)——ListenableFuture\FutureCallback\SettableFuture\Futures
- Guava并发:SettableFuture与CheckedFuture
- Guava中并发ListenableFuture使用
- Guava并发:ListenableFuture使用介绍以及示例
- Guava并发:ListenableFuture使用介绍以及示例
- guava ListenableFuture
- guava ListenableFuture
- Guava之ListenableFuture(实现Java异步)
- Guava之ListenableFuture(链式回调)
- ListenableFuture in Guava
- guava ListenableFuture使用
- ListenableFuture in Guava
- Google Guava ListenableFuture入门
- Guava 中的 ListenableFuture
- Guava ListenableFuture 小试牛刀
- ListenableFuture in Guava
- guava中的ListenableFuture
- ListenableFuture in Guava
- 溢出问题
- 华为机试——求一个字符串中的最大回文子串
- DOM的基础操作记忆
- iOS 引入字体库
- extern关键字
- Guava并发(2)——ListenableFuture\FutureCallback\SettableFuture\Futures
- Activity的跳转和传递数据
- Linux下redis的安装
- volatile关键字
- centos搭建samba服务器(新手简易篇)
- Android缓存处理
- Linux自学笔记(一)
- 带边框的文本框TextView
- React Native探索(二):布局篇