JAXBContext objects are thread safe, but initializing aΒ JAXBContext object is time consuming. This can affect the performance of applications. So we should avoid creating same JAXBContext object multiple times. Solution to address this issue is to use singleton pattern to initialize the JAXBContext object and reuse it.
public class UsersJAXBContext { private static JAXBContext instance; public UsersJAXBContext() { } public static synchronized JAXBContext getInstance() { try { if (instance == null) { instance = JAXBContext.newInstance(Users.class); } } catch (JAXBException e) { // TODO Handle the exception as required e.printStackTrace(); } return instance; } }
Now we can useΒ Marshaller
andΒ Unmarshaller
as many times as required:
Β Marshaller marshaller = UsersJAXBContext.getInstance().createMarshaller();