Skip to content
𝓒π“ͺ𝓼𝓽𝓻𝓲𝓳π“ͺ

Share the knowledge

𝓒π“ͺ𝓼𝓽𝓻𝓲𝓳π“ͺ

Share the knowledge

JAXBContext and Thread safety

Posted on February 21, 2015September 25, 2021 By sastrija

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();

Related

Uncategorized

Post navigation

Previous post
Next post
©2026 𝓒π“ͺ𝓼𝓽𝓻𝓲𝓳π“ͺ | WordPress Theme by SuperbThemes