Skip to content

Commit 55a47f9

Browse files
committed
Timeout delay scheduler thread
1 parent a833181 commit 55a47f9

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/Scheduled.kt

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
package kotlinx.coroutines.experimental
22

3-
import java.util.concurrent.Executors
43
import java.util.concurrent.ScheduledExecutorService
4+
import java.util.concurrent.ScheduledThreadPoolExecutor
55
import java.util.concurrent.TimeUnit
66
import kotlin.coroutines.startCoroutine
77

8+
val KEEP_ALIVE = java.lang.Long.getLong("kotlinx.coroutines.ScheduledExecutor.keepAlive", 50L)
9+
810
internal val scheduledExecutor by lazy<ScheduledExecutorService> {
9-
Executors.newScheduledThreadPool(1) { r ->
10-
Thread(r, "kotlinx.coroutines.ScheduledExecutor").apply { isDaemon = true }
11+
ScheduledThreadPoolExecutor(1) { r ->
12+
Thread(r, "kotlinx.coroutines.ScheduledExecutor")
13+
}.apply {
14+
setKeepAliveTime(KEEP_ALIVE, TimeUnit.MILLISECONDS)
15+
allowCoreThreadTimeOut(true)
16+
// "setRemoveOnCancelPolicy" is available only since JDK7, so try it via reflection
17+
try {
18+
val m = this::class.java.getMethod("setRemoveOnCancelPolicy", Boolean::class.javaPrimitiveType)
19+
m.invoke(this, true)
20+
} catch (ex: Throwable) { /* ignore */ }
1121
}
1222
}
1323

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package examples
2+
3+
import kotlinx.coroutines.experimental.Here
4+
import kotlinx.coroutines.experimental.delay
5+
import kotlinx.coroutines.experimental.launch
6+
7+
fun main(args: Array<String>) {
8+
launch(Here) {
9+
delay(1000L)
10+
println("World!")
11+
}
12+
println("Hello!")
13+
}

0 commit comments

Comments
 (0)