Lessons learned – Memory leak in webservices with JAXB

Lessons learned – Memory leak in webservices with JAXB

After a particularly bad performance day, we took a memory dump from our systems. It seemed the garbage collection seemed to work overtime and had difficulty cleaning up after itself. We, as such, suspected a memory leak somewhere in our code.

We bumped into the following code:

Now, after reading the documentation surrounding JAXB and its thread-safety and suggested use, this was qualified as an ‘expensive operation’. In essence, what happened is that the JAXBContext built here, never ended up getting cleaned up at garbage collection. JAXB itself suggests using the Singleton pattern when using this context, ensuring only one exists (per class). This improvement can also improve the performance of your marshalling, as you limit having to create a new instance every web service call.

We ended up with the following code:

Further reading: https://jaxb.java.net/guide/Performance_and_thread_safety.html

The memory leak was identified after noticing a buildup of garbage collection that never seemed to clear properly on our monitoring tool Dynatrace. This tool was then also used to take a memory dump during the problematic moment.

After the memory dump, we restarted our systems to ensure the GC was forced to clear and set out to investigate what the problem was before it occurred again. Dynatrace has something called a ‘memory analysis server’ which analyses the memory dump made and lists up all sorts of interesting information – including what kind of  instances are running at that moment.

Obviously, a lot of the information is going to be generic things such as Strings – but once you start looking at the high occurrence of your own classes, it is usually possible to pin down certain areas which appear problematic. Through this, we noticed the webservices using this had a lot of JAXBContext objects that simply didn’t clear.

Kevin Deyne

A 25-year-old Software Engineer with a passion for Web, Java and Writing. Working at RealDolmen, he focuses on customer-centric projects that can actually help people and move organisations forward. Most hours of the day, he's thinking about code, integrating architectures and how to solve the next big problem. He also wrote a Lovecraft-inspired thriller called Whitewood and is working on Envir, a high-end project management tool.

  • olbo

    Very nice solution. Helped me a lot by clearing a memory leak with JAXB too.

Leave a Reply