I know that sessions are not thread safe. My first question: is it safe to pass an entity to another thread, do some work to it, then pass it back to the original thread and update.
public class Example1 {
MyDao dao;
...
public void doWork() {
MyEntity entity = dao.getEntity();
Runnable job = new Job(entity);
Thread t = new Thread(job);
t.run();
t.join();
dao.merge(entity);
}
}
My second question: is it safe to new up an entity in one thread and save it in another?
public class Example2 {
MyDao dao;
...
public void doWork() {
MyEntity entity = new Entity();
new Thread(new Job(dao, entity)).run();
}
}
public class Job implements Runnable {
private MyDao dao;
private MyEntity entity;
...
@Override
public void run() {
dao.save(entity);
}
}
Edit I forgot to mention that the entities are specifically configured for eager loading
The internal state of a SessionFactory is immutable. Most problems with concurrency occur due to sharing of objects with mutable state. Once the object is immutable, its internal state is setted on creation and cannot be changed. So many threads can access it concurrently and request for sessions.
openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory. getCurrentSession() returns a session bound to a context - you don't need to close this.
When you don't close your Hibernate sessions and therefore do not release JDBC connections, you have what is typically called Connection leak. So, after a number of requests (depending on the size of your connection pool) the server will not be able to acquire a connection to respond your request.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
No. The entity is attached to the session and contains proxies linked to the session (in order to lazy-load themselves). Doing that would thus use the session from multiple threads. Since the session is not thread-safe, this is not a good idea.
While the entity is transient (i.e. you've just created it with new), it's not attached to the session, Hibernate doesn't know about it, and the entity is a plain old Java object. So no problem doing that.I don't have all the details of your DAO though. If the method of your DAO is supposed to be invoked as part of an existing transaction, that won't work, since the transaction is tied to the current thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With