Scrivio Interview library
InternalsIntermediate6 min read · updated 12 November 2026

In Spring, the EntityManager injected with @PersistenceContext is a shared proxy used by many threads. How can that be thread-safe when EntityManager itself is not?

The object Spring injects for @PersistenceContext is not a real EntityManager but a shared proxy. On every call, it looks up the EntityManager bound to the current transaction on the current thread and delegates to it; JpaTransactionManager binds that EntityManager through TransactionSynchronizationManager when the transaction starts. Each thread therefore uses its own EntityManager, and outside a transaction each call may get a new one that is closed straight afterwards, so loaded entities are detached at once. An extended persistence context is not thread-safe and rarely belongs in a singleton bean.

Why this question is asked

EntityManager is documented as not thread-safe, yet every Spring service is a singleton used by many request threads at once, and we inject an EntityManager into it as a plain field. That looks like a bug, and interviewers ask about it to see whether we understand the mechanism that makes it safe. The same mechanism explains why entities are detached outside transactions and why Spring Data repositories work the way they do. In this answer, we will see why EntityManager itself is not thread-safe, how the shared proxy works, how the transaction manager binds the real EntityManager to a thread, what happens without a transaction, and why extended contexts are different.

1Why EntityManager Itself Is Not Thread-Safe

An EntityManager owns a persistence context: a map of managed entities, their snapshots and pending changes, and usually one JDBC connection during a transaction. None of this is synchronised. If two threads used the same EntityManager, they would put entities into the same map, flush each other's changes and share a connection in the middle of different transactions. The Jakarta Persistence specification therefore says an EntityManager must not be shared between threads; it represents one unit of work.

An EntityManagerFactory, on the other hand, is thread-safe and expensive to create, so an application has one per database and creates EntityManagers from it as needed.

2What Spring Actually Injects

When Spring sees @PersistenceContext on a field, it does not inject an EntityManager created from the factory. It injects a proxy that implements the EntityManager interface, created by SharedEntityManagerCreator. The proxy holds no persistence context of its own. Every method call on it, such as find, persist or createQuery, first asks: which EntityManager belongs to the current transaction on this thread? Then it forwards the call to that one.

Java
@Repository
class ProductDao {
@PersistenceContext
private EntityManager em; // a shared proxy, safe to keep in a singleton
Product find(long id) { return em.find(Product.class, id); } // delegated per thread
}
System.out.println(em.getClass().getSimpleName()); // a JDK proxy class name such as $Proxy123, not SessionImpl

Notice that the proxy is stateless. Two threads calling em.find at the same time both go through the same proxy object, but each is forwarded to a different real EntityManager, so they never share a persistence context.

3How JpaTransactionManager Binds the Real EntityManager

When a @Transactional method starts, JpaTransactionManager creates a new EntityManager from the factory, begins a transaction on it, and registers it with TransactionSynchronizationManager. That class keeps resources in ThreadLocal maps, keyed by the factory, so the binding is visible only on the current thread. When the proxy is called, it looks up the factory's key in that map and finds the thread's EntityManager. At commit or rollback, the transaction manager flushes, ends the transaction, unbinds the EntityManager and closes it.

Step throughTwo threads, one proxy, two EntityManagers
Thread AThread BShared proxyTransactionSynchronizationManager
transaction starts: bind EntityManager A to thread A
transaction starts: bind EntityManager B to thread B
em.find(Product, 7)
resource for thread A?
EntityManager A
em.persist(order)
resource for thread B?
EntityManager B

8 messages in order. Play them, or step through them one at a time.

The proxy is shared; the EntityManagers behind it never are.

4What Happens Outside a Transaction

If the proxy is called on a thread where no transaction has bound an EntityManager, it still has to do something. For most operations it creates a new EntityManager for that one call and closes it right after. Queries are handled slightly differently: the EntityManager stays open until the query has executed, and is closed then. Either way, the persistence context lives for a single call.

The visible effect is that entities loaded outside a transaction are detached immediately. Lazy associations then fail with LazyInitializationException, and changes are never saved. Operations that modify data, such as persist, merge or flush, throw TransactionRequiredException without a transaction, because there is no unit of work for them to join.

Java
public void outside() { // no @Transactional
Product a = em.find(Product.class, 7L); // new EntityManager, SELECT, closed
Product b = em.find(Product.class, 7L); // another new EntityManager, SELECT again
System.out.println(a == b); // false: two short-lived contexts
a.getCategory().getName(); // LazyInitializationException: no session
em.persist(new Product("Lamp")); // TransactionRequiredException
}

The exception to this is Open Session in View, which binds an EntityManager to the request thread for the whole web request, so the proxy finds one even outside a transaction.

5Why Extended Persistence Contexts Are Different

JPA also has an extended persistence context, requested with @PersistenceContext(type = PersistenceContextType.EXTENDED). Here the injected EntityManager is a real one bound to the bean itself, not to a transaction, and it survives across transactions. That was designed for stateful components serving a single user conversation, such as stateful session beans.

In a Spring singleton, an extended EntityManager is shared by every thread that calls the bean, and EntityManager is not thread-safe, so concurrent requests corrupt each other's persistence context. It also grows for as long as the bean lives. Extended contexts are therefore rarely appropriate in Spring services; if they are used at all, it is in prototype or session-scoped beans used by one thread at a time.

6Follow-up questions

Is injecting EntityManager with @Autowired the same?

In Spring Boot with Spring Data JPA, constructor injection of EntityManager also gives the shared proxy, because Spring registers a shared EntityManager bean. With plain Spring, @PersistenceContext is the standard way. Either way, what we get is the transaction-aware proxy, not a raw EntityManager.

How does a Spring Data repository fit into this?

Spring Data repositories receive the same shared EntityManager proxy. Their methods are also transactional by default, read-only for queries, so a repository call outside a service transaction starts its own short transaction, binds an EntityManager, and closes it on return. That is why an entity returned by findById() outside a service transaction is already detached.

Can we use an EntityManager in a thread we start ourselves, such as in CompletableFuture?

The new thread has no transaction bound, because the binding is a ThreadLocal on the original thread. So the proxy behaves as outside a transaction there. To do transactional work in the new thread, call a @Transactional bean method or use TransactionTemplate inside that thread, and never pass managed entities between threads.

7Conclusion

In this answer, we saw that EntityManager is not thread-safe because it owns a persistence context and connection for one unit of work, and that Spring injects a stateless shared proxy instead. JpaTransactionManager creates a real EntityManager per transaction and binds it to the thread through TransactionSynchronizationManager, and the proxy forwards each call to the one bound to the current thread. Outside a transaction, each call gets a short-lived EntityManager, so entities are detached immediately and writes fail, while extended persistence contexts are bound to the bean, not the thread, and are not safe in singletons.

What to say in the interviewAbout 90 seconds aloud

Open with

What Spring injects for @PersistenceContext is not a real EntityManager, it is a shared proxy created by SharedEntityManagerCreator. The proxy has no persistence context of its own. On every call it looks up the EntityManager bound to the current transaction on the current thread and delegates to it.

Then, if they want more

That binding is done by JpaTransactionManager: when a @Transactional method starts, it creates a new EntityManager from the factory, begins the transaction, and registers it with TransactionSynchronizationManager, which keeps resources in ThreadLocals keyed by the factory. At commit it flushes, unbinds and closes it.

So many threads can share the proxy in a singleton, but each thread is routed to its own EntityManager, and they never share a persistence context or connection.

If there is no transaction on the thread, the proxy creates a temporary EntityManager for that one call, or until a query has executed, and closes it, which means loaded entities are detached immediately, lazy loading fails and persist or merge throw TransactionRequiredException. The exception is Open Session in View, which binds one for the whole request.

An extended persistence context is different: it is bound to the bean, not the transaction, so in a singleton it would be shared across threads, and it is not thread-safe, so I would not use it in Spring services.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "In Spring, the EntityManager injected with @PersistenceContext is a shared proxy used by...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/05e0e7aca7/