views:

163

answers:

4

In our system we have multi-threaded processing engine. During processing each thread calls methods to retrieve data from the database. We determined that performance is greatly improved if methods called from the same thread use the same DB session (sessions are coming from the pool of course).

Is there any standard way in Spring to ensure such thing or we have to come up with our own custom solution?

UPDATE: Forgot to mention that same methods can be called in different context where they should use a standard way of getting the session from the pool

A: 

Spring 3.0 has a concept of thread-scoped beans (hovewer, this scope is not registered by default, see docs): 3.5 Bean scopes, 3.5.5.2 Using a custom scope

EDIT: I say about this:

Thread-scoped beans As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for SimpleThreadScope. For instructions on how to register this or any other custom scope, see Section 3.5.5.2, “Using a custom scope”.

axtavt
+1  A: 

Spring has a class called TransactionSynchronizationManager. It stores the current Session in a ThreadLocal. The TransactionSynchronizationManager is not recommended for use by the developer, but you can try using it.

Session session = ((SessionHolder) 
   TransactionSynchronizationManager.getResource(sessionFactory)).getSession();

(if you are using EntityManager, simply replace "Session" with "EntityManager").

You can have the sessionFactory injected in your bean - it is per-application.

Take a look at this discussion.

Other options, which I think are preferable to manual thread-handling are:

Bozho
+1  A: 

I did not see Spring anywhere in your question. So I assume you want a simple utility to do this.

class SessionUtil {
    private ThreadLocal currentSession;

    public Session getCurrentSession() {
        if(currentSession.get() == null) {
             Session s = //create new session
             currentSession.set(s);
        }
        return (Session)currentSession.get();
    }
}

The Thread local will ensure that within the same thread it is always the same session. If you are using Spring then the classes/utilities mentioned above (in other responses) should be perfect.

Calm Storm
His question is **tagged** with spring.
BalusC
This is one of the solutions we discussed, but i was hoping to find something in Spring to make it transparent
eugener
A: 

Spring coordinates database sessions, connections and threads through it's Transaction Framework (actually, using its TransactionSynchronizationManager - see description here - but you really don't want to mess with that directly, it's fearsome). If you need to coordinate your threads, then this is by far the simplest way of doing it.

How you choose to use the framework, however, is up top you.

skaffman