Merge pull request #72 from chirino/master
Support using an executor as a function to execute a block.
This commit is contained in:
@@ -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()
|
||||
@@ -50,3 +53,26 @@ public inline fun Executor.execute(action: ()->Unit) {
|
||||
execute(runnable(action))
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows you to use the executor as a function to
|
||||
* execute the given block on the [[Executor]].
|
||||
*/
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package concurrent
|
||||
|
||||
import kotlin.concurrent.*
|
||||
import kotlin.test.*
|
||||
|
||||
import org.junit.Test as test
|
||||
|
||||
import java.util.concurrent.*
|
||||
import java.util.concurrent.TimeUnit.*
|
||||
|
||||
class ThreadTest {
|
||||
test fun scheduledTask() {
|
||||
|
||||
val pool = Executors.newFixedThreadPool(1).sure()
|
||||
val countDown = CountDownLatch(1)
|
||||
pool {
|
||||
countDown.countDown()
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user