The Hibernate documentation says that org.hibernate.Session
represents a single-threaded unit of work. I understand that unit of work is used in the context of DB transactions. What does it mean when it says single threaded? please help me in understanding this.
2 Answers
It means that you can't use the same Session instance from more than one thread, because the Session class hasn't been designed to make that possible. So, if you open a session in one thread, only this thread should use the session and the entities obtained from this session.

- 678,734
- 91
- 1,224
- 1,255
-
Thanks a lot, can you please let me know if I create 2 Java threads and try to access the session instance then will Hibernate throw exceptions in this case? – Chaitanya Aug 02 '14 at 21:24
-
It might throw an exception, but it might not be able to detect it. Don't rely on it, just don't do it. – Sanne Aug 03 '14 at 13:14
From the Session JavaDoc:
It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.
The Hibernate session is a complex object that is highly stateful (it caches objects, synchronize its internal representation with the DB, etc.). This is just a warning that if you share a session across different threads, 2 threads could be calling methods at the same time in a way that messes up the internal state of the session and cause bugs.
Hibernate has no way to "detect" that 2 threads are accessing it and may not throw exceptions. It's just not designed for it.
Wiki link about thread-safety: http://en.wikipedia.org/wiki/Thread_safety.
Program running on a single thread are simple: everything runs sequentially, so behaviours are very predictable.
OTOH, when you have 2 or more threads, they can interact with each other in unexpected ways.
E.g.:
public class NotThreadSafe {
public int internal = 0;
public void update() {
for (internal = 0; internal < 100; internal++) {
System.out.println(internal);
}
}
}
Imagine 1 instance of this class shared with 2 threads. The 1st one calls the update
method and starts iterating. While this is happening, the second thread also calls the update
method. This has the effect of resetting internal
for the first one and they will end up clashing with each other.

- 13,725
- 6
- 33
- 33