The Asyncfuntion interface is closely related to the use of function and functions for object conversion before learning to eat, asyncfuction and function need to receive an input parameter, The difference is that the Asyncfunction interface returns Listenablefuture, and we need to call the Listenablefuture.get () method when we need to receive the Asyncfunction converted results.
The Asyncfunction interface is often used when we want to perform transformations asynchronously without causing the thread to block, although the Future.get () method blocks when the task is not completed, but the Asyncfunction interface is not recommended to perform the conversion asynchronously. It is often used to return a future instance.
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));
Here is a simple simulation of a 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 via input get 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 ());
}
}
Guava Learning--asyncfunction