Browse Source

Use a thread local script engine

master
Shadowfacts 5 years ago
parent
commit
7df6669bd0
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
  1. 7
      src/main/kotlin/net/shadowfacts/ekt/EKT.kt
  2. 15
      src/test/kotlin/net/shadowfacts/ekt/Test.kt

7
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<ScriptEngine>()
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)

15
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<String>) {
val res = EKT.renderClasspath("template", "/templates", cacheDir = File("cache")) {
"list" to (listOf(1, 2, 3) asType "List<Int>")
for (i in 0..2) {
thread {
println("Calling from: $i")
render()
}
}
}
File("result.txt").apply {
if (!exists()) createNewFile()
writeText(res)
fun render(): String {
return EKT.renderClasspath("template", "/templates") {
"list" to (listOf(1, 2, 3) asType "List<Int>")
}
}
Loading…
Cancel
Save