I am working with JAXB 2.0 version. For this I am creating JAXBContext object in the following way:
package com;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
public class JAXBContextFactory {
public static JAXBContext createJAXBContext() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
return jaxbContext;
}
}
Basically since creating JAXBContext is very expensive, I want to create the JAXBContext once and only once for the entire application. So I put the JAXBContext code under static method as shown above.
Now the requests will call the JAXBContextFactory.createJAXBContext(); whenever it needs reference to JAXBContex. Now my question is , in this case is the JAXBContext created only once or will the application have multiple instances of JAXBContext?
Your application will have one instance of JAXBContext for each time this method is called.
If you do not want this to happen, you need to do the following thing
The difference between this and your implementation is that in this one, we save the instance of JAXBContext that was created in a static variable (which is guaranteed to exist only once). In your implementation you are not saving the instance you just created anywhere, and will just create a new instance every time the method is called. Important: do not forget the
synchronizedkeyword added to the method declaration, as it makes sure that calling this method in a multi-threaded environment will still work as expected.