Created
February 6, 2017 11:40
-
-
Save eldargab/22b30a7d0dcfc7e2d36970d5b8b3a777 to your computer and use it in GitHub Desktop.
Simpler thread-safe jaxb marshalling - unmarshalling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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