JAXB creating context and marshallers cost

后端 未结 8 2102
情深已故
情深已故 2020-11-28 02:00

The question is a bit theoretical, what is the cost of creating JAXB context, marshaller and unmarshaller?

I\'ve found that my code could benefit from keeping the sa

8条回答
  •  無奈伤痛
    2020-11-28 02:48

    I solved this problem using:

    • shared thread safe JAXBContext and thread local un/marschallers
    • (so theoretically, there will be as many un/marshaller instances as there are threads which accessed them)
    • with synchronization only on un/marshaller's initialization.
    public class MyClassConstructor {
        private final ThreadLocal unmarshallerThreadLocal = new ThreadLocal() {
            protected synchronized Unmarshaller initialValue() {
                try {
                    return jaxbContext.createUnmarshaller();
                } catch (JAXBException e) {
                    throw new IllegalStateException("Unable to create unmarshaller");
                }
            }
        };
        private final ThreadLocal marshallerThreadLocal = new ThreadLocal() {
            protected synchronized Marshaller initialValue() {
                try {
                    return jaxbContext.createMarshaller();
                } catch (JAXBException e) {
                    throw new IllegalStateException("Unable to create marshaller");
                }
            }
        };
    
        private final JAXBContext jaxbContext;
    
        private MyClassConstructor(){
            try {
                jaxbContext = JAXBContext.newInstance(Entity.class);
            } catch (JAXBException e) {
                throw new IllegalStateException("Unable to initialize");
            }
        }
    }
    

提交回复
热议问题