如何提高使用JAXBContext.newInstance操作的应用程序的性能? [英] How do I improve performance of application that uses the JAXBContext.newInstance operation?

查看:422
本文介绍了如何提高使用JAXBContext.newInstance操作的应用程序的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基于JBoss的Web应用程序中使用JAXBContext.newInstance操作。据我所知,这项行动是非常重量级的。我只需要Marshaller类的两个唯一实例。

I use the JAXBContext.newInstance operation in my JBoss based web application. This operation, as I understand, is very heavyweight. I only require two unique instances of the Marshaller class.

我的初始建议是有一个静态初始化程序块,只在类加载时初始化这两个实例:

My initial proposal is to have a static initializer block that will initialize these two instances only once upon the class loading:

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(...);
            ...
    }

}

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

If this is a reasonable solution then I guess I'll have answered my own question, but I would like to know if this is the correct way to do this?

推荐答案

JAXB实现( Metro EclipseLink MOXy Apache JaxMe 等通常在 JAXBContext.newInstance 调用期间初始化其元数据。所有OXM工具都需要在某个时刻初始化映射元数据,并尝试最小化此操作的成本。由于无法以零成本完成,因此最好只进行一次。 JAXBContext的实例是线程安全的,所以是的,你只需要创建一次。

A JAXB implementation (Metro, EclipseLink MOXy, Apache JaxMe, etc) typically initializes its metadata during the JAXBContext.newInstance call. All OXM tools need to initialize mapping metadata at some point and try to minimize the cost of this operation. Since it is impossible to do it with zero cost, it is best to only do it once. Instances of JAXBContext are thread safe, so yes you only need to create it once.

从JAXB 2.2规范,第4.2节JAXB上下文:

From the JAXB 2.2 Specification, Section 4.2 JAXB Context:


为避免在
中创建JAXBContext实例所涉及的开销,鼓励
JAXB应用程序以
重用JAXBContext实例。抽象类

实现JAXBContext需要是
线程安全的,因此,
中的多个线程应用程序可以共享相同的
JAXBContext实例。

To avoid the overhead involved in creating a JAXBContext instance, a JAXB application is encouraged to reuse a JAXBContext instance. An implementation of abstract class JAXBContext is required to be thread-safe, thus, multiple threads in an application can share the same JAXBContext instance.

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

Instances of Marshaller and Unmarshaller are not thread safe and must not be shared among threads, they are lightweight to create.

这篇关于如何提高使用JAXBContext.newInstance操作的应用程序的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆