Skip to content

Commit 9ffcc70

Browse files
committed
#172 pre-calculate transformer
1 parent ec692e1 commit 9ffcc70

1 file changed

Lines changed: 30 additions & 19 deletions

File tree

src/main/java/com/jcabi/xml/XSLDocument.java

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
import java.nio.file.Path;
4444
import java.util.HashMap;
4545
import java.util.Map;
46+
import java.util.concurrent.atomic.AtomicReference;
4647
import javax.xml.parsers.DocumentBuilder;
4748
import javax.xml.parsers.DocumentBuilderFactory;
4849
import javax.xml.parsers.ParserConfigurationException;
@@ -139,6 +140,13 @@ public final class XSLDocument implements XSL {
139140
*/
140141
private final transient String sid;
141142

143+
/**
144+
* Cached transformer.
145+
* @since 0.26
146+
*/
147+
private final transient AtomicReference<Transformer> cached =
148+
new AtomicReference<>();
149+
142150
/**
143151
* Public ctor, from XML as a source.
144152
* @param src XSL document body
@@ -417,27 +425,30 @@ private void transformInto(final XML xml, final Result result) {
417425
* @return The transformer
418426
*/
419427
private Transformer transformer() {
420-
final Transformer trans;
421-
synchronized (XSLDocument.TFACTORY) {
422-
XSLDocument.TFACTORY.setURIResolver(this.sources);
423-
try {
424-
trans = XSLDocument.TFACTORY.newTransformer(
425-
new StreamSource(new StringReader(this.xsl), this.sid)
426-
);
427-
} catch (final TransformerConfigurationException ex) {
428-
throw new IllegalArgumentException(
429-
String.format(
430-
"Failed to create transformer by %s",
431-
XSLDocument.TFACTORY.getClass().getName()
432-
),
433-
ex
434-
);
428+
if (this.cached.get() == null) {
429+
final Transformer trans;
430+
synchronized (XSLDocument.TFACTORY) {
431+
XSLDocument.TFACTORY.setURIResolver(this.sources);
432+
try {
433+
trans = XSLDocument.TFACTORY.newTransformer(
434+
new StreamSource(new StringReader(this.xsl), this.sid)
435+
);
436+
} catch (final TransformerConfigurationException ex) {
437+
throw new IllegalArgumentException(
438+
String.format(
439+
"Failed to create transformer by %s",
440+
XSLDocument.TFACTORY.getClass().getName()
441+
),
442+
ex
443+
);
444+
}
435445
}
446+
for (final Map.Entry<String, Object> ent : this.params.entrySet()) {
447+
trans.setParameter(ent.getKey(), ent.getValue());
448+
}
449+
this.cached.set(XSLDocument.forSaxon(trans));
436450
}
437-
for (final Map.Entry<String, Object> ent : this.params.entrySet()) {
438-
trans.setParameter(ent.getKey(), ent.getValue());
439-
}
440-
return XSLDocument.forSaxon(trans);
451+
return this.cached.get();
441452
}
442453

443454
/**

0 commit comments

Comments
 (0)