Skip to content

Commit d810bbf

Browse files
committed
Use a ThreadLocal to allow reusing parser instances
Currently scala-xml creates a new SAXParser instance every time. This is not very good for performance, but explained by the fact that SAXParser is not thread safe. We can greatly increase performance by using a ThreadLocal, giving each thread their own instance.
1 parent 3eb5453 commit d810bbf

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

shared/src/main/scala/scala/xml/factory/XMLLoader.scala

+11-6
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,18 @@ trait XMLLoader[T <: Node] {
2323
import scala.xml.Source._
2424
def adapter: FactoryAdapter = new NoBindingFactoryAdapter()
2525

26-
/* Override this to use a different SAXParser. */
27-
def parser: SAXParser = {
28-
val f = SAXParserFactory.newInstance()
29-
f.setNamespaceAware(false)
30-
f.newSAXParser()
26+
private lazy val parserInstance = new ThreadLocal[SAXParser] {
27+
override def initialValue = {
28+
val parser = SAXParserFactory.newInstance()
29+
30+
parser.setNamespaceAware(false)
31+
parser.newSAXParser()
32+
}
3133
}
3234

35+
/* Override this to use a different SAXParser. */
36+
def parser: SAXParser = parserInstance.get
37+
3338
/**
3439
* Loads XML from the given InputSource, using the supplied parser.
3540
* The methods available in scala.xml.XML use the XML parser in the JDK.
@@ -58,4 +63,4 @@ trait XMLLoader[T <: Node] {
5863

5964
/** Loads XML from the given String. */
6065
def loadString(string: String): T = loadXML(fromString(string), parser)
61-
}
66+
}

0 commit comments

Comments
 (0)