【问题标题】:How to set a value asynchronously and fetch it at a later stage如何异步设置一个值并在稍后阶段获取它
【发布时间】: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


    【解决方案1】:

    IMO,使用CompletableFuture,您可以更轻松地异步设置数字。这是一种可能的方法:

    public CompletableFuture<Model> setNumberAsync() {
        return CompletableFuture.supplyAsync(() -> helper.decrypt())
                .thenCombine(stepsBeforeSettingNumber(), (number, model) -> {
                    MyObj myObj = model.myObj;
                    myObj.setNumber(number);
                    if (myObj.getNumber() == 100) {
                        // do something
                    }
                    return model;
                });
    }
    
    public CompletableFuture<Model> stepsBeforeSettingNumber() {
        //  going to various other classes / methods 
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多