Home » Java » java – EntityManager is null when use in parallelStream-Exceptionshub

java – EntityManager is null when use in parallelStream-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an EJB bean which have a method that call another method from the bean with parallel stream. It works fine, but in the async method I must update entity in the db and when I call entityManager.merge than I got a NullPointerExpcetion. I don’t know why.

I use OpenJPA on WebSphere.

The original question was: Call a method for List in parallel?

@Stateless
public class TestBean implements LocalInterface, RemoterInterface {
    @PersistenceContext(unitName = Constants.PERSISTENCE_UNIT)
    protected EntityManager entityManager;

    public void a(List<Object> list) {
        for(Object o : list) {
            asynchMethod(o); // this n method call must run in the same time
        }

        // wait for all asynchMethod result
        /**
         * ...other statements
         */
    }

    private void asynchMethod(Object o) {
        o.setSomeField(value);
        entityManager.merge(o); // NullPointerException
    }
}
How to&Answers: