Today, I was working a newsletter program in Java using the Hibernate library.  I decided to use the ScrollableResults object because I do not have to load all of the database entity at once.  Instead, I can use a database cursor to retrieve the entity one by one.

At the beginning, I wrote this code.

ScrollableResults userCursor = query.scroll();
while (userCursor.next()) {
    User user = (User)userCursor.get(0);
    // do action
}

Our database has around 200,000 users and the program seems to be working fine. Later on, we put this code in a multi-threaded environment with 5 threads, and the program runs slower and slower.  A few minutes later, I saw this message in the console:


Caused by: java.lang.OutOfMemoryError: Java heap space

After struggling for a while, I found out that the problem occurs because the User object is still “connected” to the session.  To correctly fix this problem, we must flush and clear the hibernate session.

The new code will be:

ScrollableResults userCursor = query.scroll();
while (userCursor.next()) {
   User user = (User)userCursor.get(0);
   // do action
   session.flush();
   session.clear();
}

Or you can also call session.evict(object);

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required