|
| 1 | +package com.cas_parser.api.core |
| 2 | + |
| 3 | +import java.util.concurrent.Callable |
| 4 | +import java.util.concurrent.ExecutorService |
| 5 | +import java.util.concurrent.Future |
| 6 | +import java.util.concurrent.TimeUnit |
| 7 | + |
| 8 | +/** |
| 9 | + * A delegating wrapper around an [ExecutorService] that shuts it down once it's only phantom |
| 10 | + * reachable. |
| 11 | + * |
| 12 | + * This class ensures the [ExecutorService] is shut down even if the user forgets to do it. |
| 13 | + */ |
| 14 | +internal class PhantomReachableExecutorService(private val executorService: ExecutorService) : |
| 15 | + ExecutorService { |
| 16 | + init { |
| 17 | + closeWhenPhantomReachable(this) { executorService.shutdown() } |
| 18 | + } |
| 19 | + |
| 20 | + override fun execute(command: Runnable) = executorService.execute(command) |
| 21 | + |
| 22 | + override fun shutdown() = executorService.shutdown() |
| 23 | + |
| 24 | + override fun shutdownNow(): MutableList<Runnable> = executorService.shutdownNow() |
| 25 | + |
| 26 | + override fun isShutdown(): Boolean = executorService.isShutdown |
| 27 | + |
| 28 | + override fun isTerminated(): Boolean = executorService.isTerminated |
| 29 | + |
| 30 | + override fun awaitTermination(timeout: Long, unit: TimeUnit): Boolean = |
| 31 | + executorService.awaitTermination(timeout, unit) |
| 32 | + |
| 33 | + override fun <T : Any?> submit(task: Callable<T>): Future<T> = executorService.submit(task) |
| 34 | + |
| 35 | + override fun <T : Any?> submit(task: Runnable, result: T): Future<T> = |
| 36 | + executorService.submit(task, result) |
| 37 | + |
| 38 | + override fun submit(task: Runnable): Future<*> = executorService.submit(task) |
| 39 | + |
| 40 | + override fun <T : Any?> invokeAll( |
| 41 | + tasks: MutableCollection<out Callable<T>> |
| 42 | + ): MutableList<Future<T>> = executorService.invokeAll(tasks) |
| 43 | + |
| 44 | + override fun <T : Any?> invokeAll( |
| 45 | + tasks: MutableCollection<out Callable<T>>, |
| 46 | + timeout: Long, |
| 47 | + unit: TimeUnit, |
| 48 | + ): MutableList<Future<T>> = executorService.invokeAll(tasks, timeout, unit) |
| 49 | + |
| 50 | + override fun <T : Any?> invokeAny(tasks: MutableCollection<out Callable<T>>): T = |
| 51 | + executorService.invokeAny(tasks) |
| 52 | + |
| 53 | + override fun <T : Any?> invokeAny( |
| 54 | + tasks: MutableCollection<out Callable<T>>, |
| 55 | + timeout: Long, |
| 56 | + unit: TimeUnit, |
| 57 | + ): T = executorService.invokeAny(tasks, timeout, unit) |
| 58 | +} |
0 commit comments