2

我是java.util.concurrent包装新手,我遇到了Future对象问题。

这是一个对话范围的 bean。

@Inject SomeBean stateFull;

Boolean comp = false, comp1 = false;

public void doSomething(){        

    stateFull.runProcess();   

    try {

        comp = stateFull.getFuture().get();    
        System.out.println("Future "+syncEJB.getFuture().get());
        updateView();

        comp1 = stateFull.getFuture1().get();   
        System.out.println("Future "+syncEJB.getFuture().get());
        updateView();

    } catch (InterruptedException ex) {
        Logger.getLogger(SynchronizationMB.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ExecutionException ex) {
        Logger.getLogger(SynchronizationMB.class.getName()).log(Level.SEVERE, null, ex);
    }


}

SomeBean 看起来像这样。

@Stateful
public class SomeBean{    

    @Inject AnotherBean stateLess;

    private volatile Future<Boolean> future, future1;

    @Asynchronous
    public void runProcess(){
        future = stateLess.compute(); 
        future1 = stateLess.compute(); 

    }
    public Future<Boolean> getFuture() {
        return future;
    }
    public Future<Boolean> getFuture1() {
        return future1;
    }
}

还有另一个豆子:

@Stateless
public class AnotherBean{

@Asynchronous
public Future<Boolean> compute() {
    boolean result;


    System.out.println("--------------");
    System.out.println("completed sync");
    System.out.println("--------------");

    result = true;

    return new AsyncResult<Boolean>(result);
}
}

现在我的问题。我调用doSomething()方法,我认为根据它的文档Future.get()应该调用runProcess(),而不是等到
comp = stateFull.getFuture().get();
SomeBean 中的未来从 AnotherBean 完成,但它只是继续抛出NullPointerException. 任何人都知道为什么会发生这种情况?

- - - - - - - - - -编辑 - - - - - - - - - - - -

NullPointer 已得到纠正。现在我有另一个问题。假设我通过在 runProcess() 中调用更多方法在 Somebean 中设置了更多 Future 对象。然后我想在每次 Future 对象获得结果以查看进度时更新我的​​页面。我怎么做?现在我用

private void updateView(){
    RequestContext ctx = RequestContext.getCurrentInstance();
    ctx.update("mainFrm:info");
}

在 doSomething() 方法中的每个布尔值下,但它没有做我想要的。所有布尔值都一次出现。

4

1 回答 1

3

NPE 发生是因为启动新线程是一项繁重的操作,并且当您调用stateFull.getFuture().get();新线程时尚未启动(因此功能为空)。

这里@Async是使用Future的正确方法。

于 2012-08-17T11:47:34.067 回答