Defensive Flushing with Hibernate

We were hunting down potential performance killers in our application over the last few weeks. Everything came to mind from slow algorithms, ineffective class-mapping, even problems with Hibernate (the usual suspects, too many queries, inefficient SQL, and the like). Even using custom SQL came up, but what do you know, one single point of tuning was enough to give the all-over performance a tremendous boost. When using HQL queries in your application, be sure to disable automatic flushing wherever you can. Hibernate by default flushes all changes to the database, when you fire a query. And that includes dirty-checking all objects in the session cache. The profiling showed that most of the time was spent in QueryImpl.list() in most profiled scenarios. When you get to the bottom of it all you find Hibernate calling your object’s getters millions and millions of times. The number rises exponentially with the number of persistent objects you’re using in a single transaction. I don’t blame Hibernate for this, it’s just the way it works, and you have to know that.

So what can you do, if you need to query? Do what Jason Carreirarecommends and define your flushing strategy early. We didn’t do it, and we paid the price of having to find the problem later. So what we did is, whenever we fire a HQL query, we tell the session to flush on commit:

Session session = SessionFactory.openSession();
session.setFlushMode(FlushMode.COMMIT);
// fire your query

The result was overwhelming. The overall performance improved dramatically. We’re talking factors of 60. Of course we had to fix some code accordingly, but it was worth it.

If you do or plan on doing the same, stay clear of relying on flushed data in your code. If you changed some data without flushing the session explicitly, you might end up with inconsistent data when querying the database. The problems will become fewer, if you keep your transactions small. That’s why I can only recommend what Jason already recommended: Define your flushing strategy early.

Leave a Reply

You must be logged in to post a comment.