Utils.java Source code

Java tutorial

Introduction

Here is the source code for Utils.java

Source

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

public class Utils {
    private static DocumentBuilderFactory dbf;

    private static Queue builders = new ConcurrentLinkedQueue();

    public static DocumentBuilder getBuilder() throws ParserConfigurationException {
        DocumentBuilder builder = (DocumentBuilder) builders.poll();
        if (builder == null) {
            if (dbf == null) {
                dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true);
            }
            builder = dbf.newDocumentBuilder();
        }
        return builder;
    }

    public static void releaseBuilder(DocumentBuilder builder) {
        builders.add(builder);
    }

    /**
     * Return a new document, ready to populate.
     * 
     * @return
     * @throws ParserConfigurationException
     */
    public static Document newDocument() throws ParserConfigurationException {
        DocumentBuilder builder = getBuilder();
        Document doc = builder.newDocument();
        releaseBuilder(builder);
        return doc;
    }

}