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

查看:28
本文介绍了如何提高使用 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天全站免登陆