'Hibernate cache clearing with JPA2, concurrent threads and a connection pool

In a Spring application using JPA2 with Hibernate, we run multiple tasks in parallel. The tasks each have their own transaction:

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = {ForceRollbackException.class})
public void doTaskRun(CallableTask callableTask) throws ForceRollbackException {

    try {
        callableTask.getActualTask().runTask();
    } catch (Exception e){
        callableTask.getLog().error("Task execution threw an Exception: " + e.getLocalizedMessage(), e);
        throw new ForceRollbackException("Forcing rollback because the task threw an Exception", e);
    }

}

The database connections are provided by a connection pool.

Our memory usage when running these tasks goes up a lot. When no tasks are being executed anymore, the memory usage stays high, even after GC. Investigation of the heap dump indicates that a lot of memory is being used by Hibernate.

Ideally, we would want to clear the session cache once a task is done, but I'm in need of more background information. The examples I find, e.g. here, seem to deal with a single-thread application. How will this impact a multi-threaded application? Is it possible that the session will be shared by multiple transactions, which could be multiple tasks running in parallel? Obviously we don't want to clear objects that other threads might still be using...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source