title: java multithreading on dom apis
body: <p>I have a function that does xml parsing. I want to make the function thread safe, but also as optimized (less blocking) as possible.<br>
  In short code is something as follows:</p>
  
  <pre><code>public Document doXML(InputStream s)
  {
  //Some processing.
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document xmlDoc = parser.parse(is);
    return xmlDoc;
  
  }
  </code></pre>
  
  <p>But I do not want to create a new DocumentBuilderFactory or DocumentBuilder in each call.<br>
  I want to reuse factory and parser, but I am not sure they are thread-safe. So what is the most optimal approach?<br>
  <strong>1)</strong> Cache a DocumentBuilderFactory in a class field and synchronize the  factory.newDocumentBuilder(); so that each thread has its own instance of DocumentBuilder<br>
  <strong>2)</strong> Cache a DocumentBuilderFactory <strong>and</strong> DocumentBuilder and <strong>synchronize parser.parse(is);</strong> per thread<br>
  I think (2) is best, but is it safe to do it?  Also can I avoid blocking by synchronized? I would like it to be as fast as possible.</p>
  
  <p>Thanks?</p>