persistence@glassfish.java.net

Unexpected close of EM

From: Michael Bouschen <Michael.Bouschen_at_Sun.COM>
Date: Fri, 12 May 2006 15:07:32 +0200

Hi Tom,

the recent persistence drop adds a finalize method to the EMF
implementation in entity-persistence module. This closes the EMF which
then closes all open EMs created by this factory. With this change my
simple J2SE test case runs into an IllegalStateException saying
"Attempting to execute an operation on a closed EntityManager." when
creating a new query instance.

The reason is that I used the following pattern to create an EM:
   EntityManager em =
     Persistence.createEntityManagerFactory("pu").createEntityManager();
Please note, I do not keep a reference to the EMF. Since the EM does not
hold a strong reference to the EMF, the garbage collector can remove the
EMF instance which then in turn closes the EM that is still used by the
application.

I'm not recommending this code pattern. However, to avoid the above
scenario I propose the EM implementation should hold a strong reference
to its factory. Then the factory cannot be garbage collected as long as
as there is an EM around created by this factory.

What do you think? Do you want me to create a glassfish issue for this?

Attached you find a jar including a single test case that can be used to
reproduce the problem. You need to adapt the properties in build.xml and
persistence.xml to your local environment and then call 'ant'.

Regards Michael