Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

java - Hibernate session thread safety

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. 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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...