16
16
17
17
package kotlinx.coroutines.experimental
18
18
19
+ import java.io.Closeable
19
20
import java.util.concurrent.Executor
21
+ import java.util.concurrent.ExecutorService
20
22
import java.util.concurrent.RejectedExecutionException
21
23
import java.util.concurrent.ScheduledExecutorService
22
24
import java.util.concurrent.TimeUnit
23
25
import kotlin.coroutines.experimental.CoroutineContext
24
26
27
+ /* *
28
+ * [CoroutineDispatcher] that implements [Closeable]
29
+ */
30
+ abstract class CloseableCoroutineDispatcher : CoroutineDispatcher (), Closeable
31
+
32
+ /* *
33
+ * Converts an instance of [ExecutorService] to an implementation of [CloseableCoroutineDispatcher].
34
+ */
35
+ public fun ExecutorService.asCoroutineDispatcher (): CloseableCoroutineDispatcher =
36
+ // we know that an implementation of Executor.asCoroutineDispatcher actually returns a closeable one
37
+ (this as Executor ).asCoroutineDispatcher() as CloseableCoroutineDispatcher
38
+
25
39
/* *
26
40
* Converts an instance of [Executor] to an implementation of [CoroutineDispatcher].
27
41
* @suppress **Deprecated**: Renamed to [asCoroutineDispatcher].
@@ -42,7 +56,7 @@ private class ExecutorCoroutineDispatcher(override val executor: Executor) : Exe
42
56
/* *
43
57
* @suppress **This is unstable API and it is subject to change.**
44
58
*/
45
- public abstract class ExecutorCoroutineDispatcherBase : CoroutineDispatcher (), Delay {
59
+ public abstract class ExecutorCoroutineDispatcherBase : CloseableCoroutineDispatcher (), Delay {
46
60
/* *
47
61
* @suppress **This is unstable API and it is subject to change.**
48
62
*/
@@ -77,6 +91,10 @@ public abstract class ExecutorCoroutineDispatcherBase : CoroutineDispatcher(), D
77
91
return DefaultExecutor .invokeOnTimeout(time, unit, block)
78
92
}
79
93
94
+ override fun close () {
95
+ (executor as ? ExecutorService )?.shutdown()
96
+ }
97
+
80
98
override fun toString (): String = executor.toString()
81
99
override fun equals (other : Any? ): Boolean = other is ExecutorCoroutineDispatcherBase && other.executor == = executor
82
100
override fun hashCode (): Int = System .identityHashCode(executor)
0 commit comments