Skip to content

Instantly share code, notes, and snippets.

@eldargab
Created February 6, 2017 11:40
Show Gist options
  • Select an option

  • Save eldargab/22b30a7d0dcfc7e2d36970d5b8b3a777 to your computer and use it in GitHub Desktop.

Select an option

Save eldargab/22b30a7d0dcfc7e2d36970d5b8b3a777 to your computer and use it in GitHub Desktop.
Simpler thread-safe jaxb marshalling - unmarshalling
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.Callable;
/**
* Simpler thread-safe jaxb marshalling - unmarshalling
*/
public class Jaxb {
private ThreadLocal<Unmarshaller> unmarshaller;
private ThreadLocal<Marshaller> marshaller;
public Jaxb(JAXBContext jaxb) {
this.unmarshaller = ThreadLocal.withInitial(() -> safe(jaxb::createUnmarshaller));
this.marshaller = ThreadLocal.withInitial(() -> safe(jaxb::createMarshaller));
}
public Jaxb(Class ...classes) {
this(safe(() -> JAXBContext.newInstance(classes)));
}
private static <T> T safe(Callable<T> fn) {
try {
return fn.call();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Object unmarshal(InputStream is) throws JAXBException {
return unmarshaller.get().unmarshal(is);
}
public Object unmarshal(File f) throws JAXBException {
return unmarshaller.get().unmarshal(f);
}
public void marshal(Object jaxbElement, OutputStream os) throws JAXBException {
marshaller.get().marshal(jaxbElement, os);
}
public void marshal(Object jaxbElement, File output) throws JAXBException {
marshaller.get().marshal(jaxbElement, output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment