簡體   English   中英

DocumentBuilder.parse()線程安全嗎?

[英]Is DocumentBuilder.parse() thread safe?

標准的Java 1.6 javax.xml.parsers.DocumentBuilder類是否安全? 從多個線程並行調用parse()方法是否安全?

JavaDoc沒有提到這個問題,但Java 1.4中同一類JavaDoc明確表示它並不意味着並發; 所以我可以假設在1.6中它是?

原因是我在ExecutorService中運行了數百萬個任務,每次調用DocumentBuilderFactory.newDocumentBuilder()似乎都很昂貴。

即使DocumentBuilder.parse看起來不會改變它在Sun JDK默認實現(基於Apache Xerces)上的構建器。 偏心的設計決定。 你能做什么? 我想使用ThreadLocal:

private static final ThreadLocal<DocumentBuilder> builderLocal =
    new ThreadLocal<DocumentBuilder>() {
        @Override protected DocumentBuilder initialValue() {
            try {
                return
                    DocumentBuilderFactory
                        .newInstance(
                            "xx.MyDocumentBuilderFactory",
                            getClass().getClassLoader()
                        ).newDocumentBuilder();
            } catch (ParserConfigurationException exc) {
                throw new IllegalArgumentException(exc);
            }
        }
    };

(免責聲明:與嘗試編譯代碼不同。)

DocumentBuilder上有一個reset()方法,它將其恢復到首次創建時的狀態。 如果您正在使用ThreadLocal路線,請不要忘記給它打電話或者你已經開了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM