46 lines
1.2 KiB
Kotlin
46 lines
1.2 KiB
Kotlin
package util.future
|
|
|
|
import kotlinx.coroutines.GlobalScope
|
|
import kotlinx.coroutines.Job
|
|
import kotlinx.coroutines.isActive
|
|
import kotlinx.coroutines.launch
|
|
import java.lang.reflect.InvocationHandler
|
|
import java.lang.reflect.Method
|
|
import java.lang.reflect.Proxy
|
|
import java.util.concurrent.LinkedBlockingQueue
|
|
import java.util.concurrent.TimeUnit
|
|
|
|
class FutureHandler(private val target: Any) : InvocationHandler {
|
|
private val queue = LinkedBlockingQueue<LatchFuture<*>>()
|
|
|
|
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any {
|
|
val future = method!!.invoke(target, *args!!) as LatchFuture<*>
|
|
queue.add(future)
|
|
|
|
return future
|
|
}
|
|
|
|
fun start(): Job {
|
|
return GlobalScope.launch {
|
|
while (isActive || queue.isNotEmpty()) {
|
|
queue.poll(100, TimeUnit.MILLISECONDS)
|
|
?.exec()
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fun <T> Any.toFutureHandler(inter: Class<T>): Pair<T, Job> {
|
|
val futureHandler = FutureHandler(this)
|
|
|
|
val job = futureHandler.start()
|
|
|
|
return Pair(
|
|
Proxy.newProxyInstance(
|
|
this::class.java.classLoader,
|
|
arrayOf(inter),
|
|
futureHandler
|
|
) as T, job
|
|
)
|
|
}
|