标签:fabs 实例 ati 接收 get new int 线程 exception
AsyncFuntion接口与之前学习吃的使用Function和Functions进行对象转换有很密切的联系,AsyncFuction和Function都需要接收一个input参数,不同的是AsyncFunction接口返回的是 ListenableFuture,当我们需要接收AsyncFunction转换后的结果时,我们需要调用 ListenableFuture.get()方法。
AsyncFunction接口常被用于当我们想要异步的执行转换而不造成线程阻塞时,尽管Future.get()方法会在任务没有完成时造成阻塞,但 是AsyncFunction接口并不被建议用来异步的执行转换,它常被用于返回Future实例。
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
public class AsyncFunctionSample implements AsyncFunction<Long, String> {
private ConcurrentMap<Long, String> map = Maps.newConcurrentMap();
private ListeningExecutorService listeningExecutorService =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));
// 这里简单的模拟一个service
private Map<Long, String> service = new HashMap<Long, String>() {
{
put(1L, "retrieved");
}
};
@Override
public ListenableFuture<String> apply(final Long input) throws Exception {
if (map.containsKey(input)) {
SettableFuture<String> listenableFuture = SettableFuture.create();
listenableFuture.set(map.get(input));
return listenableFuture;
} else {
return listeningExecutorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// service中通过input获取retrieved
String retrieved = service.get(input);
map.putIfAbsent(input, retrieved);
return retrieved;
}
});
}
}
public static void main(String[] args) throws Exception {
AsyncFunctionSample afs = new AsyncFunctionSample() {
@Override
public ListenableFuture<String> apply(Long input) throws Exception {
return super.apply(input);
}
};
System.out.println(afs.apply(1L).get());
}
}
标签:fabs 实例 ati 接收 get new int 线程 exception
原文地址:http://www.cnblogs.com/fanguangdexiaoyuer/p/6250759.html