Java XPathFactory 线程安全 [英] Java XPathFactory thread-safety

查看:22
本文介绍了Java XPathFactory 线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javax.xml.XPathFactory.newInstance() 线程安全吗?

Is javax.xml.XPathFactory.newInstance() thread-safe?

我之所以这么问,是因为我发现文档对此有歧义.JDK 5 文档根本没有提到线程安全;在 JDK 6 中,他们写了以下内容:

I'm asking because I find the documentation ambiguous for it. The JDK 5 docs don't mention thread-safety at all; in JDK 6 they wrote the following:

XPathFactory 类不是线程安全的.换句话说,它是应用程序有责任确保最多只有一个线程在任何给定时刻使用 XPathFactory 对象.实现是鼓励将方法标记为同步以保护自己免受坏客户.

The XPathFactory class is not thread-safe. In other words, it is the application's responsibility to ensure that at most one thread is using a XPathFactory object at any given moment. Implementations are encouraged to mark methods as synchronized to protect themselves from broken clients.

据我所知,为 XPathFactory 单独实现是不安全的,但这样做应该是安全的:

As I understand it, it's not safe to have a singleton implementation for XPathFactory, but doing something like this should be safe:

XPath xPathEvaluator = XPathFactory.newInstance().newXPath();

我错过了什么吗?它是否取决于扩展它的实际类?我是否需要同步包含上述语句的方法?

Am I missing something? Does it depend on the actual class that extends it? Do I need to synchronize the method that contains the above statement?

推荐答案

XPath xPathEvaluator = XPathFactory.newInstance().newXPath();

XPath xPathEvaluator = XPathFactory.newInstance().newXPath();

这是安全的,因为每个线程都有自己的工厂(感谢 newInstance()).此处无需同步.

That is safe, because every thread gets its own factory (thanks to newInstance()). No need to synchronize here.

你不能安全地做的是只获取一次工厂,然后在没有同步的情况下在线程之间共享它,例如作为单例.XPath 实例 (xPathEvaluator) 本身也是如此.

What you cannot safely do is get the factory just once, and then share it between threads without synchronization, for example as a singleton. The same goes for the XPath instance (xPathEvaluator) itself.

这篇关于Java XPathFactory 线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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