Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is DocumentBuilder.parse() thread safe?

Is the standard Java 1.6 javax.xml.parsers.DocumentBuilder class thread safe? Is it safe to call the parse() method from several threads in parallel?

The JavaDoc doesn't mention the issue, but the JavaDoc for the same class in Java 1.4 specifically says that it isn't meant to be concurrent; so can I assume that in 1.6 it is?

The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.

like image 610
Avi Avatar asked Sep 11 '08 14:09

Avi


People also ask

Is Documentbuilder thread safe?

An implementation of the DocumentBuilderFactory class is NOT guaranteed to be thread safe. It is up to the user application to make sure about the use of the DocumentBuilderFactory from more than one thread. Alternatively the application can have one instance of the DocumentBuilderFactory per thread.

Why do we use DocumentBuilderFactory in Java?

Class DocumentBuilderFactory. Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents. Allows the user to retrieve specific attributes on the underlying implementation.


1 Answers

Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a 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);             }         }     }; 

(Disclaimer: Not so much as attempted to compile the code.)

like image 182
Tom Hawtin - tackline Avatar answered Sep 20 '22 19:09

Tom Hawtin - tackline