Java tutorial
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Main { private static final Map<Class<?>, SoftReference<JAXBContext>> contextCache = new HashMap<>(); /** * @since 2.4 */ public static Marshaller createMarshaller(final Object object) throws JAXBException { JAXBContext context = createContext(object.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); return marshaller; } /** * Returns a cached <i>JAXB Context</i>. * * @since 3.8 */ public synchronized static JAXBContext createContext(final Class<?> bind) throws JAXBException { JAXBContext context = null; SoftReference<JAXBContext> ref = contextCache.get(bind); if (ref != null) { context = ref.get(); if (context == null) contextCache.remove(bind); } if (context != null) return context; synchronized (bind) { synchronized (JAXBContext.class) { context = JAXBContext.newInstance(bind); } } contextCache.put(bind, new SoftReference<JAXBContext>(context)); return context; } }