JAXBContext and Thread safety

JAXBContext is thread safe, but initializing a JAXBContext object is time consuming. This can also lead to performance of the application. Due to this reason we should avoid creating a JAXBContext object multiple times. Implementing singleton pattern as below will resolve this issue, and it is thread safe.

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
        return instance;


Now from your code you can create as many marshaling and unmarshaling. Since we have synchronized in method it is thread safe now.

Now we can use Marshaller and Unmarshaller as many times as required:

 Marshaller marshaller = UsersJAXBContext.getInstance().createMarshaller();


Leave a Reply

Your email address will not be published. Required fields are marked *