logo

JAXB and OutOfMemoryError

How to solve two common reasons for OutOfMemoryError, which you may encounter using JAXB.

First of all, there may be many reasons why OutOfMemoryError pops up. But with JAXB I encountered mainly two reasons.

 

The first one is that you have a too large XML file. You can increase your Java heap memory using -Xmx. If the file is really big or if you just increased the heap memory and it works but it's too slow, you may need to use SAX to parse this XML file. So no JAXB for you.

 

The second reason is if you have a method which runs periodically and inside you create a instance of JAXBContext. It's important to have just single instance of this class in the whole application. You can ensure that by having this object as a static attribute.

 

Bad:

 

JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);

 

Good:

 

  private static JAXBContext jaxbContext;
  
  static {
    try {
      jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    } catch (JAXBException e) {
      e.printStackTrace();
    }
  }

 


comments powered by Disqus

rss

Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects:
github

Search