JAXB工具类JAXBContext为什么耗时约来越高?

JAXB工具类 JAXBContext主要用来将实体类与xml字符串的转换,常见的使用方式如下:

但是在实际测试中发现,当并发线程达到一定量的时候会导致性能急剧下降,耗时增高,实际测试100次耗时结果如下:

 

 

 

原因为每次在调用该工具类时都会调用实例化实体类

JAXBContext context = JAXBContext.newInstance(obj.getClass());

通过源码反编译可以看到底层实现方式,每次都会生成一个新的实例。

 

 

 

随着线程数增大,该功能耗时会更高,测试结果如下:

10   最高耗时:30毫秒、26毫秒、28毫秒

100  最高耗时:1452毫秒、1816毫秒、1754毫秒

1000 最高耗时:22787毫秒、25044毫秒、23137毫秒

很明显,随着使用线程数的增高,性能急剧下降。

解决方案:

JAXBContext context = JAXBContext.newInstance(obj.getClass());

改为

JAXBContext context = jAXBContextMap.get(obj.getClass().getName());

if (null == context) {

context = JAXBContext.newInstance(obj.getClass());

jAXBContextMap.put(obj.getClass().getName(), context);

}

将已经实例化的JAXBContext实例存储在map中,每次使用都先从map获取map中不存在则创建,并放入map。

测试一下,测试用例如下

 

 

 

 

实际测试结果:

方式一:如上面的测试结果。

方式二:

10次结果

100次结果

 

1000次结果:

根据测试结果可以看出,修改后的除第一次创建实例时候耗时外,后续都是无需耗时的。

 

posted @ 2021-11-09 15:00  不会飞的机器猫  阅读(466)  评论(0编辑  收藏  举报