如何提高使用JAXBContext.newInstance操作的应用程序的性能?

我在基于JBoss的Web应用程序中使用JAXBContext.newInstance操作。据我了解,此操作非常繁重。我只需要Marshaller类的两个唯一实例。

我最初的建议是要有一个静态初始值设定项块,该类将在加载类时仅初始化一次这两个实例:

public class MyWebApp {

private static Marshaller requestMarshaller;

private static Marshaller responseMarshaller;

static {

try {

// one time instance creation

requestMarshaller = JAXBContext.newInstance(Request.class).createMarshaller();

responseMarshaller = JAXBContext.newInstance(Response.class).createMarshaller();

} catch (JAXBException e) {

e.printStackTrace();

}

}

private void doSomething() {

requestMarshaller.marshall(...);

responseMarshaller.marshall(...);

...

}

}

如果这是一个合理的解决方案,那么我想我会回答自己的问题,但是我想知道这是否是正确的方法?

回答:

JAXB实现(Metro,EclipseLink

MOXy,Apache

JaxMe等)通常在JAXBContext.newInstance调用期间初始化其元数据。所有OXM工具都需要在某个时候初始化映射元数据,并尝试最小化此操作的成本。由于不可能用零成本做到这一点,因此最好只做一次。JAXBContext的实例是线程安全的,因此,您只需创建一次即可。

根据JAXB 2.2规范的第4.2节JAXB上下文:

为了避免创建JAXBContext实例所涉及的开销,鼓励JAXB应用程序重用JAXBContext实例。抽象类JAXBContext的实现必须是线程安全的,因此,应用程序中的多个线程可以共享同一JAXBContext实例。

Marshaller和Unmarshaller的实例不是线程安全的,并且不能在线程之间共享,它们的创建是轻量级的。

以上是 如何提高使用JAXBContext.newInstance操作的应用程序的性能? 的全部内容, 来源链接: utcz.com/qa/400176.html

回到顶部