@@ -39,19 +39,40 @@ public class EntityManagerController implements AutoCloseable
3939 protected final List <EntityManager > activeEms = Collections .synchronizedList (new ArrayList <>());
4040 protected final EntityManagerFactory emf ;
4141
42+ protected boolean closeEntityManagerOnCleanupWithoutCheck = true ;
43+
4244 public EntityManagerController (final EntityManagerFactory emf )
4345 {
4446 this .emf = Objects .requireNonNull (emf );
4547 }
4648
49+ /**
50+ * Should it be assumed that each {@link EntityManager} was NOT closed and the {@link EntityManager#isOpen()}
51+ * can be
52+ * skipped?
53+ * <p>
54+ * Setting this to {@code true} improves performance.
55+ * </p>
56+ * <p>
57+ * {@code true} by default as Entity Managers are assumed to be container(=framework) managed <br/>and not
58+ * application(=developer) managed and "randomly" closed during operations.
59+ * </p>
60+ * <p>
61+ * Setting this option to {@code false} usually indicates major design flaws in the corresponding code.
62+ * </p>
63+ */
64+ public EntityManagerController closeEntityManagerOnCleanupWithoutCheck (
65+ final boolean closeEntityManagerOnCleanupWithoutCheck )
66+ {
67+ this .closeEntityManagerOnCleanupWithoutCheck = closeEntityManagerOnCleanupWithoutCheck ;
68+ return this ;
69+ }
70+
4771 /**
4872 * Creates a new {@link EntityManager} with an internal {@link EntityManagerFactory}, which can be used to load and
4973 * save data in the database.
5074 *
5175 * <p>
52- * It may be a good idea to close the EntityManager, when you're finished with it.
53- * </p>
54- * <p>
5576 * All created EntityManager are automatically cleaned up once {@link #close()} is called.
5677 * </p>
5778 *
@@ -77,7 +98,11 @@ public void close()
7798 {
7899 em .getTransaction ().rollback ();
79100 }
80- em .close ();
101+
102+ if (this .closeEntityManagerOnCleanupWithoutCheck || !em .isOpen ())
103+ {
104+ em .close ();
105+ }
81106 }
82107 catch (final Exception e )
83108 {
0 commit comments