Java EE future 的空指针

标签 java multithreading jakarta-ee concurrency java.util.concurrent

我是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;
    }
}

还有另一个Bean:

@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 中的 future 从 AnotherBean 完成,但它只是不断抛出 NullPointerException 。有人知道为什么会发生这种情况吗?

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

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

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

在 doSomething() 方法中的每个 boolean 值下,但它没有执行我想要的操作。所有 boolean 值都会同时出现。

最佳答案

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

Here@Async 与 Future 一起使用的正确方法。

关于Java EE future 的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12004922/

相关文章:

java - 自动增加 JLabel

multithreading - 如何在 Swift 中创建 volatile bool 值?

c++ - QtWebEngine - 同步执行 JavaScript 以读取函数结果

java - 如何在 Metro/JavaEE 自动生成的 WSDL 中自定义命名空间前缀?

java - 如何部署 Web 应用程序

java - 如何允许两种类型的数据作为参数

Java检查鼠标按钮状态

c++ - CPP : How to create a thread with method that requires pointer?

Java ME 和 Java EE 通信

java - 在 Android 的 Canvas 上绘制一个又一个形状