【发布时间】:2019-09-23 16:00:23
【问题描述】:
我希望异步设置变量的值。之后,我想在稍后阶段获得该值。我怎样才能做到这一点?这就是我目前正在做的事情。这是一个正确的实现还是我应该选择 CompletableFuture?
当进行休息调用时,这是第一个被调用的方法之一。
public class A{
@Autowired
private Helper helper;
private final ExecutorService executor = Executors.newFixedThreadPool(10);
public void stepOne(Model model) {
MyObj myObj = model.myObj;
// helper.decrypt() returns a String
Future<String> futureNumber = executor.submit(() -> helper.decrypt());
myObj.setFutureNumber(futureNumber);
}
}
// coming to following method after awhile going to various other classes / methods
// now I need the value myObj.getFutureNumber().
public class B{
public void stepTwo(Model model) {
// model should now have the value 100
MyObj myObj = model.myObj;
final String number = null;
try{
myObj.setNumber(myObj.getFutureNumber().get());
}catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if(myObj.getNumber() == 100){
// do something
}
}
}
这是我的对象
public class MyObj{
private String number;
private Future<String> futureNumber;
// get set methods
}
【问题讨论】:
标签: java java.util.concurrent completable-future