Search code examples
hibernatehibernate-session

What it means that Hibernate Session is single threaded?


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.


Solution

  • 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.