Java : 带有 ListenableFuture 的番石榴期货 API
Java : guava Futures API with ListenableFuture
我试图通过简单的例子更好地理解番石榴 API:
首先我实例化 returns "hello" 的 ListenableFuture
然后我使用 Futures.transform() 将我的 "hello" 转换为 "HELLO"
但是我没有结果。
这是我的代码(我删除了 ListenableFuture 实现中的其他方法以使事情变得更容易):
public static void main(String[] args) throws InterruptedException, ExecutionException {
ListenableFuture<String> future = getString();
ListenableFuture<String> future2 = Futures.transform(future, new Function<String,String>() {
@Override
public String apply(String input) {
return input.toUpperCase();
}
});
System.out.println(future.get()); //print "hello"
System.out.println(future2.get()); //blocking, never ends...no result
}
private static ListenableFuture<String> getString() {
return new ListenableFuture<String>() {
@Override
public String get() throws InterruptedException, ExecutionException {
return "hello";
}
};
}
这可能表示 "other methods in the ListenableFuture implementation" 中存在错误,您已将其删除以简化操作。
不要实施您自己的 ListenableFuture
,而是使用 Futures.immediateFuture("hello")
以获得正确的实施。
我试图通过简单的例子更好地理解番石榴 API: 首先我实例化 returns "hello" 的 ListenableFuture 然后我使用 Futures.transform() 将我的 "hello" 转换为 "HELLO" 但是我没有结果。
这是我的代码(我删除了 ListenableFuture 实现中的其他方法以使事情变得更容易):
public static void main(String[] args) throws InterruptedException, ExecutionException {
ListenableFuture<String> future = getString();
ListenableFuture<String> future2 = Futures.transform(future, new Function<String,String>() {
@Override
public String apply(String input) {
return input.toUpperCase();
}
});
System.out.println(future.get()); //print "hello"
System.out.println(future2.get()); //blocking, never ends...no result
}
private static ListenableFuture<String> getString() {
return new ListenableFuture<String>() {
@Override
public String get() throws InterruptedException, ExecutionException {
return "hello";
}
};
}
这可能表示 "other methods in the ListenableFuture implementation" 中存在错误,您已将其删除以简化操作。
不要实施您自己的 ListenableFuture
,而是使用 Futures.immediateFuture("hello")
以获得正确的实施。