The current code base that I am looking at uses the DOM parser. The following code fragment is duplicated in 5 methods :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
If a method that contains the above code is called in a loop or the method is called multiple times in the application, we are bearing the overhead of creating a new DocumentBuilderFactory instance and a new DocumentBuilder instance for each call to such a method.
Would it be a good idea to create a singleton wrapper around the DocumentBuilder factory and DocumentBuilder instances as shown below :
public final class DOMParser {
private DocumentBuilderFactory = new DocumentBuilderFactory();
private DocumentBuilder builder;
private static DOMParser instance = new DOMParser();
private DOMParser() {
builder = factory.newDocumentBuilder();
}
public Document parse(InputSource xml) {
return builder.parser(xml);
}
}
Are there any problems that can arise if the above singleton is shared across multiple threads? If not, will there be any performance gain by using the above approach of creating the DocumentBuilderFactory and the DocumentBuilder instances only once throughout the lifetime of the application?
Edit :
The only time we can face a problem is if DocumentBuilder saves some state information while parsing an XML file which can affect the parsing of the next XML file.