Search code examples
asynchronousjakarta-eeejbcdi

Access session bean member variable from EJB asynchronous method


I have a @SessionScoped bean (CDI) that I would like to access and update from a EJB @Asynchronous method. If I pass a reference to a member variable in the bean via the @Asynchronous method's parameters and work with it, assuming the object being passed in is made thread safe, is there any other issues I should be aware of?

Is there any different to be aware if a @ViewScoped bean is used instead?

The only one I could think of would be if the CDI Session Bean timed out however that shouldn't be an issue because the object would be retained as the @Asynchronous method still has a reference to it.

I'm trying to pass off a long running task so as not to hold up the user clicking on a button but still update the session model with the result of the job so the user can see the outcome in a "job viewer" type interface.


Solution

  • Never access frontend classes from backend classes.

    Just pass a callback to the EJB method.

    @Asynchronous
    public void asyncDoSomething(SomeInput input, Consumer<SomeResult> callback) {
        SomeResult result = doSomethingWith(input); 
        callback.accept(result);
    }
    

    public void yourSessionScopedBeanMethod() {
        yourEjb.asyncDoSomething(input, this::setResult);
    }
    
    public void setResult(SomeResult result) {
        this.result = result;
    }