JavaAssist and CGLIB Hibernate and Spring

I recently came across some legacy code that brought to mind some interesting aspects of Spring and Hibernate. This involves the code generation libaray CGLIB.

Javassist is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it.

Cglib It is used to extend JAVA classes and implements interfaces at runtime.

Hibernate v 3.2 and below utilize CGLIB to generate proxies for the database connections. Hibernate v3.3 and above use Javassist by default.

The way CGLIB (Older version 2.1.1 this should be fixed in new versions) generates proxies causes the memory to contain a lot of used but referenced objects hence increasing the size of the heap. So much so that the heap will grow until we get a Out Of Memory Error. This happens just before a proxy is instantiated when using the CGLIBLazyInitializer.getProxy().  

Please refer to for more information. First and formost Spring managed Hibernate sessions and transactions can be very powerful and have advantages such as cleaning up of sessions.  However combining Spring with Hibernate v3.2 and below leads to memory mismanagement due to the CGLIB which has some internal issues.

If you are however stuck to modifying or maintaining applications that are utilizing CGLIB you could add the following code snipplet to improve performance and fix the above issue:

cfg.setListeners("load", new LoadEventListener [] {new DefaultLoadEventListener(), new LoadEventListener() {

            public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException {

                Object obj = event.getResult();

                if (obj instanceof HibernateProxy) {






The cfg variable is the configuration variable of hibernate.

In addition when upgrading to Hibernate v3.5 be aware that it implements strick checks on whether SQL queries are well formed.

Having implemented Hibernate v3.5 some of my memory issues were gone and the application was left in a stable state.



About gjcbell

I am the Cloud Architect at IBM. I work in and create Hybrid Cloud solutions. These are solutions that have an on premise facet and multi Cloud platform facet. My area of focus spans the Bluemix Platform, IBM Cloud Private as well as cloud brokerage.
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s