Java Reference
In-Depth Information
XML and JSON parser factories are expensive to create. Fortunately the factories are thread-safe,
so it is easy to store the factory in a global static variable and reuse the factory as needed.
In general, the actual parsers cannot be reused, nor are they thread-safe. Parsers, therefore, are
usually created on demand.
One advantage of the SAX parser is that it allows the parser object to be reused. In order to reuse
the parser, call its reset() method in between parser invocations. The parser is still not thread-
safe, however, so make sure to limit its reuse to within a single thread at a time.
Let's look at those points in order.
In these tests, the data stream is parsed 1 million times in order to find the average parsing
speed (after a warm-up period of 10,000 parses). The example code needs to make sure it
constructs the factory only once, which is done in an initialization method called at the be-
ginning of the test. The actual parser for each test is then retrieved via the factory on demand.
Hence the SAX test contains this code:
SAXParserFactory spf ;
// Called once on program initialization
protected void
throws IOException {
spf = SAXParserFactory . newInstance ();
void engineInit ( RunParams rp ) throws
// Called each iteration
protected XMLReader getReader () Throws SAXException {
return spf . newSAXParser (). getXMLReader ();
The StAX parser looks similar, though the factory (of type XMLInputFactory ) is returned
from calling the XMLFactory.newInstance() method, and the reader is returned from call-
ing the createStreamReader() method. For JSON, the corresponding calls are the
Json.createParserFactory() and createParser() methods.
To use a different parser implementation, we must start with a different factory, so that the
call to the factory returns the desired implementation. This brings us to the second point
about factory configuration: make sure the factory to use is optimally specified.
XML factories are specified by setting a property in one of three ways. The property used in
the discussion here ( ) is the property for the default
Search WWH ::

Custom Search