Skip to content

Instantly share code, notes, and snippets.

@cwash
Last active December 18, 2015 23:29
Show Gist options
  • Save cwash/5861860 to your computer and use it in GitHub Desktop.
Save cwash/5861860 to your computer and use it in GitHub Desktop.
Singleton that follows the Initialization-on-demand idiom to initialize and front a thread-safe JAXBContext object.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class JAXBContextLoader
{
private final Map<String, JAXBContext> contextMap;
private JAXBContextLoader()
{
contextMap = new ConcurrentHashMap<String, JAXBContext>();
}
public static JAXBContext getJAXBContext(String contextPath)
{
JAXBContextLoader loader = JAXBContextLoaderHolder.instance;
if (loader.contextMap.containsKey(contextPath))
{
return loader.contextMap.get(contextPath);
}
else
{
try
{
JAXBContext jaxbContext = JAXBContext.newInstance(contextPath);
loader.contextMap.put(contextPath, jaxbContext);
return jaxbContext;
} catch (JAXBException e)
{
throw new RuntimeException(e);
}
}
}
private static class JAXBContextLoaderHolder
{
private static final JAXBContextLoader instance = new JAXBContextLoader();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment