首页 > 解决方案 > 多线程 Java 应用程序中的 xpathFactory 问题

问题描述

我有 xpathutility 类,我在整个应用程序中使用它来从 xpath 表达式获取字符串或节点结果:

public static String getStringResult(String expression, Document doc) {
        String outString = new String();

        try {
            outString = (String)xpath.compile(expression).evaluate(doc, XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            e.printStackTrace(System.out);
        }
        return outString;
    }
    public static NodeList getNodeListResult(String expression, Document doc) {
        NodeList outList = null;

        try {
            outList = (NodeList)xpath.compile(expression).evaluate(doc, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace(System.out);
        }
        return outList;
    }

对于工厂的初始化,我使用了以下内容,以使线程安全,通过互联网找到它:

 private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>()
    {
        @Override
        protected XPathFactory initialValue()
        {
            return XPathFactory.newInstance();
        }
    };
    private static final XPath xpath= XPATH_FACTORY.get().newXPath();

但是当我从多个线程执行它时,它给了我对 xpath 的空指针期望。需要知道如何使其线程安全。

标签: javamultithreadingxpaththread-local

解决方案


推荐阅读