[jboss-as7-dev] JTA Synchronization.afterCompletion callback can occur in a background thread but JPA EntityManager must be accessed in single-threaded manner...

Scott Marlow smarlow at redhat.com
Fri Feb 22 16:53:11 EST 2013


On 02/22/2013 04:17 PM, Jason Greene wrote:
>
> On Feb 22, 2013, at 3:13 PM, Scott Marlow <smarlow at redhat.com> wrote:
>
>>
>> I'm closing the entity manager because its a JPA spec (7.9.1) requirement for the container to close it:
>>
>> "After the JTA transaction has completed (either by transaction commit or rollback), the container closes the entity manager calling EntityManager.close.
>> "
>
> We don't have to interpret it literally. When the transaction rolls back (either via exception or getStatus) take the exact same action that EntityManager.close would take.

The JPA container managed code might not know that the transaction has 
completed (in the application thread), as the afterCompletion occurs in 
the background thread.

>
>>
>> If I don't close it, the GC might be able to clean it up for us but that depends on whether there are any strong references to it.  The transaction will get GCd, so the transaction reference to the EntityManager will disappear.  This has potential to create a memory leak.
>
> No need for GC. We *know* the outcome of the transaction, and we control the implementation of the entity manager, therefore we can close it in the application thread.

After the background thread commits or rolls back the transaction, the 
application thread may not make any further EntityManager calls, so 
can't depend on the EntityManager getting control again.

If we can't depend on returning to the top level container (I agree with 
what you said about that), how about a component level interceptor that 
processes an afterCompletion queue after each invocation?

>
> --
> Jason T. Greene
> JBoss AS Lead / EAP Platform Architect
> JBoss, a division of Red Hat
>



More information about the jboss-as7-dev mailing list