Pooling javax.xml.parsers.DocumentBuilder objetcs!!


General J2EE: Pooling javax.xml.parsers.DocumentBuilder objetcs!!

  1. Hi all,

    I'm writing a kind of "WebService" which consists to perform requests (and also responses...)in XML. To service users I'm using a Servlet but the problem is that this application will be requested by approximatively 1000 users simultanously, and the creation of the response via the javax.xml.parsers.DocumentBuilder object consumes a lot of ressources, so my question is : is there a way to pool these objects (i'm open also for a better solution!).

    i'll be grateful for any response,

    PS : i'm using WSAD, JAXP, Struts

    Nabil BENMIRA
  2. A simple object pool is not hard to write:

    import java.util.*;
    import javax.xml.parsers.*;

    public class DocBuilderPool {
      private static final Map POOL = new WeakHashMap();
      private static int keyCounter = 0;

      public synchronized static DocumentBuilder getBuilder()
        throws ParserConfigurationException {
        Iterator iterator = POOL.values().iterator();
        if (iterator.hasNext()) {
          return (DocumentBuilder) iterator.next();
        } else {
          return DocumentBuilderFactory.newInstance().newDocumentBuilder();

      public synchronized static void release(DocumentBuilder builder) {
        POOL.put(nextKey(), builder);

      private synchronized static Integer nextKey() {
        return new Integer(POOL.size() + 1);

    In your servlet:

    DocumentBuilder builder = DocBuilderPool.getBuilder();
    // Use the builder ...

    The code is a bit more complicated than it really need to be, because I wanted to use a WeakHashMap that will allow for garbage collection during low load times. A more complex pool might set an upper limit on the number of DocumentBuilders that will be created.
  3. Jakarta Commons Pool[ Go to top ]