{"record":{"id":"32d9bd693bbbda92","repo":"flowable/flowable-engine","slug":"error-while-closing-entitymanager-may-have-alread","errorCode":null,"errorMessage":"Error while closing EntityManager, may have already been closed or it is container-managed","messagePattern":"Error while closing EntityManager, may have already been closed or it is container-managed","errorType":"exception","errorClass":"FlowableException","httpStatus":null,"severity":"error","filePath":"modules/flowable-variable-service/src/main/java/org/flowable/variable/service/impl/types/EntityManagerSessionImpl.java","lineNumber":78,"sourceCode":"                throw new FlowableException(\"Error while flushing EntityManager: \" + pe.getMessage(), pe);\n            }\n        }\n    }\n\n    protected boolean isTransactionActive() {\n        if (handleTransactions && entityManager.getTransaction() != null) {\n            return entityManager.getTransaction().isActive();\n        }\n        return false;\n    }\n\n    @Override\n    public void close() {\n        if (closeEntityManager && entityManager != null && entityManager.isOpen()) {\n            try {\n                entityManager.close();\n            } catch (IllegalStateException ise) {\n                throw new FlowableException(\"Error while closing EntityManager, may have already been closed or it is container-managed\", ise);\n            }\n        }\n    }\n\n    @Override\n    public EntityManager getEntityManager() {\n        if (entityManager == null) {\n            entityManager = getEntityManagerFactory().createEntityManager();\n\n            if (handleTransactions) {\n                // Add transaction listeners, if transactions should be handled\n                TransactionListener jpaTransactionCommitListener = new TransactionListener() {\n                    @Override\n                    public void execute(CommandContext commandContext) {\n                        if (isTransactionActive()) {\n                            entityManager.getTransaction().commit();\n                        }\n                    }","sourceCodeStart":60,"sourceCodeEnd":96,"githubUrl":"https://github.com/flowable/flowable-engine/blob/d6d39ce1c69ff244f2d9dc6af756a9b95e865586/modules/flowable-variable-service/src/main/java/org/flowable/variable/service/impl/types/EntityManagerSessionImpl.java#L60-L96","documentation":"At session close, Flowable calls entityManager.close() only if the EntityManager is application-managed and still open. If the JPA provider throws IllegalStateException during close ( EntityManager already closed, or container-managed so the application must not close it), this FlowableException is thrown.","triggerScenarios":"EntityManagerSession.close() invoked while the underlying EntityManager is already closed or is container-managed (e.g. injected via @PersistenceContext in a Java EE/Spring container) and closeEntityManager was configured true.","commonSituations":"Mixing container-managed persistence (Spring/Java EE) with Flowable's JPA variable handling; double-closing a session; custom EntityManagerFactory configuration that pre-closes or shares EMs across threads.","solutions":["Configure Flowable to NOT close the EntityManager when it is container-managed (set closeEntityManager false in EntityManagerSessionFactory)","Ensure the EntityManagerFactory passed to Flowable creates application-managed EntityManagers","Check for code paths that close the EntityManager before the session close runs","Review Spring/EE config so the same EM isn't shared and closed elsewhere"],"exampleFix":"// before\nEntityManagerFactory emf = Persistence.createEntityManagerFactory(\"containerManagedUnit\");\nnew EntityManagerSessionFactory(emf, true, true); // handleTransactions, closeEntityManager=true\n// after\nnew EntityManagerSessionFactory(emf, true, false); // let the container manage EM lifecycle","handlingStrategy":"try-catch","validationCode":"// configuration check before engine use\nif (usingContainerManagedEm) {\n    assert engineConfigJpaFactory.isCloseEntityManager() == false;\n}","typeGuard":"boolean safeToClose(EntityManager em) { return em != null && em.isOpen(); }","tryCatchPattern":"try { session.close(); } catch (FlowableException e) { log.warn(\"EntityManager close skipped: {}\", e.getMessage()); } // close-time failure is non-fatal to business logic","preventionTips":["Set closeEntityManager=false when the EntityManager is container-managed (Spring @PersistenceContext, Java EE)","Never manually close EntityManagers owned by Flowable sessions","Use one EntityManagerFactory per engine and let Flowable own its lifecycle"],"tags":["jpa","entitymanager","lifecycle","flowable"],"backgroundTag":"invalid-state-transition","analyzedSha":"d6d39ce1c69ff244f2d9dc6af756a9b95e865586","analyzedAt":"2026-09-11T06:41:19.413Z","contentChangedAt":"2026-09-11T06:41:19.413Z","schemaVersion":2},"datasetVersion":"2026-09-14T11:17:12.474Z"}