Viswesh J
Viswesh J

Reputation: 29

lifetime of Entitymanager instance

I have a requirement in which we create a single Statelebean which creates a Container Managed EntityManager instance(using @PersistenceContext) in EJB3 environment. In this single Stateless bean created, we create threads which are executed in specific time intervals. This thread would be running for months. I have a doubt as to whether the single EntityManager instance obtained from the container (using CMP) can be used for the entire lifetime(> 1yrs).

Upvotes: 2

Views: 585

Answers (2)

Chris
Chris

Reputation: 21165

An EntityManager seems meant to represent a transactional space. To me, it doesn't make sense to use a single transactional space for the entire life of a thread that will be long lived but it depends on your design and provider implementation how feasible this is. If you are going to use a single EM, make sure it is not shared between threads, and monitor its resource usage, as they are required by JPA to cache every entity read through them as managed instances; you might want to occasionally call em.clear() to detach managed instances so they can be garbage collected at logical points.

I don't think injection will work, as the container should tie the EntityManager to the life of the bean it is injected into, not the life of your thread. You will want to obtain the EntityManagerFactory and obtain/manage your own EntityManager lifecycles for your threads.

Upvotes: 1

V G
V G

Reputation: 19002

To the lifetime of EntityManager: I think it is more a question of the DB connection lifetime. In this case, when the JPA provider detects a connection time-out, if you configured your JDBC connection string wth autoReconnect=true you would expect that another connection is built. Also you should search for possibilities of setting a big timeout.

On the other side, you probably ignore that in EJB you are not allowed to open new Threads. In your case, you would have some problems when it comes to managed entities (that are changed in different threads) and to transaction problems. Instead I would use the Timer Service.

Upvotes: 1

Related Questions