Adding support for transforming functions into Callable objects and integration with ExecutorService.

This commit is contained in:
Hiram Chirino
2012-07-18 14:55:50 -04:00
parent 7cbb8a19fb
commit ac434d4852
3 changed files with 39 additions and 0 deletions
+11
View File
@@ -4,6 +4,7 @@ import java.util.ArrayList
import java.util.Collection
import java.util.HashSet
import java.util.LinkedList
import java.util.concurrent.Callable
/**
Helper to make jet.Iterator usable in for
@@ -77,3 +78,13 @@ public inline fun runnable(action: ()-> Unit): Runnable {
}
}
}
/**
* A helper method for creating a [[Callable]] from a function
*/
public inline fun <T> callable(action: ()-> T): Callable<T> {
return object: Callable<T> {
public override fun call() = action()
}
}
@@ -1,6 +1,9 @@
package kotlin.concurrent
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Future
import java.util.concurrent.Callable
inline val currentThread : Thread
get() = Thread.currentThread().sure()
@@ -58,3 +61,18 @@ public inline fun Executor.invoke(action: ()->Unit) {
execute(runnable(action))
}
/**
* Executes the given block on the [[Executor]]
*/
public inline fun <T>ExecutorService.submit(action: ()->T):Future<T> {
val c:Callable<T> = callable(action)
return submit(c).sure();
}
/**
* Allows you to use the executor as a function to
* execute the given block on the [[Executor]].
*/
public inline fun <T>ExecutorService.invoke(action: ()->T):Future<T> {
return submit(action)
}
@@ -18,4 +18,14 @@ class ThreadTest {
}
assertTrue(countDown.await(2, SECONDS), "Count down is executed")
}
test fun callableInvoke() {
val pool = Executors.newFixedThreadPool(1).sure()
val future = pool<String> {
"Hello"
}
assertEquals("Hello", future.get(2, SECONDS))
}
}