From 7df6669bd00b903186ef391980cba8459ba18249 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Wed, 30 Aug 2017 19:35:26 -0400 Subject: [PATCH] Use a thread local script engine --- src/main/kotlin/net/shadowfacts/ekt/EKT.kt | 7 ++++--- src/test/kotlin/net/shadowfacts/ekt/Test.kt | 17 +++++++++++------ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/src/main/kotlin/net/shadowfacts/ekt/EKT.kt b/src/main/kotlin/net/shadowfacts/ekt/EKT.kt index c68776b..51ee215 100644 --- a/src/main/kotlin/net/shadowfacts/ekt/EKT.kt +++ b/src/main/kotlin/net/shadowfacts/ekt/EKT.kt @@ -2,8 +2,10 @@ package net.shadowfacts.ekt import java.io.File import javax.script.ScriptContext +import javax.script.ScriptEngine import javax.script.ScriptEngineManager import javax.script.SimpleScriptContext +import kotlin.concurrent.getOrSet /** * @author shadowfacts @@ -42,9 +44,7 @@ fun include(include: String, init: net.shadowfacts.ekt.EKT.DataProvider.() -> Un _result.toString() """ - private val engine by lazy { - ScriptEngineManager().getEngineByExtension("kts") - } + private val engine = ThreadLocal() fun render(env: TemplateEnvironment, template: String = env.template): String { if (env.cacheDir != null && env.cacheFile.exists()) { @@ -122,6 +122,7 @@ _result.toString() } internal fun eval(script: String, env: TemplateEnvironment): String { + val engine = engine.getOrSet { ScriptEngineManager().getEngineByExtension("kts") } engine.context = SimpleScriptContext() val bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE) bindings.putAll(env.data) diff --git a/src/test/kotlin/net/shadowfacts/ekt/Test.kt b/src/test/kotlin/net/shadowfacts/ekt/Test.kt index 830bcdf..9757c82 100644 --- a/src/test/kotlin/net/shadowfacts/ekt/Test.kt +++ b/src/test/kotlin/net/shadowfacts/ekt/Test.kt @@ -1,17 +1,22 @@ package net.shadowfacts.ekt import java.io.File +import kotlin.concurrent.thread /** * @author shadowfacts */ fun main(args: Array) { - val res = EKT.renderClasspath("template", "/templates", cacheDir = File("cache")) { + for (i in 0..2) { + thread { + println("Calling from: $i") + render() + } + } +} + +fun render(): String { + return EKT.renderClasspath("template", "/templates") { "list" to (listOf(1, 2, 3) asType "List") } - - File("result.txt").apply { - if (!exists()) createNewFile() - writeText(res) - } } \ No newline at end of file