JAXB Context rule for memory leak

When new instance of JAXBContext is created, it creates a small memory leak.
It is a bad bractice to create a new instance every time xml is read.

JaxbContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

Instead jaxbContext should be created only once - for example as static variable

Hello Jiri,

I’m afraid that if we simply raise an issue on each JAXBContext.newInstance call, we will raise a lot of FPs.

Could you be more precise about what you would consider as a bad way to declare a JAXBContext? … and a good way to declare it?

Thanks

Hello,

bad practice is declaring the JAXBContext as a local variable inside a method - example

private Object parseXML(byte){
JAXBContext context = JAXBContext.newInstance(…);

return data;
}

This way each time method is used, it allocates new jaxbclasses that are never used.
Better way is to have a JAXBContext in a field or maybe a static block, so it is allocated only once

// JAXBContext is thread-safe
private static final JAXBContext CONTEXT;

static {
    try {
        CONTEXT = JAXBContext.newInstance("........");
    } catch (JAXBException e) {
        throw new RuntimeException("Error occurred initializing jaxbContext", e);
    }
}

More details can be found here:

https://javaee.github.io/jaxb-v2/doc/user-guide/ch03.html#other-miscellaneous-topics-performance-and-thread-safety

This is the best practise how to use jaxb