Skip to content

Conversation

SantanuKar43
Copy link

This PR fixes a bug in JpaLocalTxnInterceptor where a broken EntityManager could remain in a thread’s ThreadLocal after a failed transaction, leading to subsequent requests failing when the same thread is reused by the web server (e.g., Jetty).

Problem

  • Guice Persist stores the EntityManager in a ThreadLocal.
  • If a transaction fails due to a database connection issue (e.g., network blip):
  • txn.isActive() incorrectly returns false because the connection is already dead.
  • The cleanup logic is skipped due to this check.
  • The broken EntityManager is never removed from the ThreadLocal.
  • When the thread is reused for another request, the stale EntityManager is returned, causing immediate failures.

Fix

  • Updated cleanup logic to always remove the EntityManager from the ThreadLocal if this interceptor started the work, regardless of txn.isActive().
  • Reorganized the try/catch/finally blocks so that commit/rollback semantics remain correct while ensuring cleanup runs after transaction handling.
  • Ensures no broken EntityManager instances leak into future requests.

Related Issue

Fixes #1916 and #1179

@SantanuKar43
Copy link
Author

@sameb @lukesandberg can you please review this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

EntityManager leak in ThreadLocal when connection is lost during transaction
1 participant