Last active
December 19, 2015 04:18
-
-
Save takawitter/5895868 to your computer and use it in GitHub Desktop.
ThreadPoolExecutorに値を返すlambda(or closure)をsubmitしたい。submit(Callable<T> task)が呼ばれればOKなんだけど、ThreadPoolExecutorにはsubmit(Runnable task)も存在するので、普通にlambdaを渡すと曖昧性が解消できない。そのためCallable<T>を明示する必要があるが、その方法が言語によって違うって話。 ScalaとJythonとJRubyは直接やる方法が無さそうなので、ラッパークラスをかましてる。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* tp は Executors.newCachedThreadPool 等を使って生成 | |
*/ | |
// Rhino(JavaScript) | |
tp.submit(new Callable({call: function(){ return 1;}})); | |
// Groovy | |
tp.submit({1} as Callable) | |
// Scala | |
def asCallable[T](f:()=>T): Callable[T] = new Callable[T](){ def call() = f()} | |
tp.submit(asCallable(()=>1)) | |
# Jython | |
class CallableWrapper(Callable): | |
def __init__(self, f): | |
self.f = f | |
def call(self): | |
return self.f() | |
tp.submit(CallableWrapper(lambda : 1)) | |
# JRuby | |
class CallableWrapper | |
include Callable | |
def initialize(f) | |
@f = f | |
end | |
def call() | |
@f.call() | |
end | |
end | |
tp.submit(CallableWrapper.new(lambda{1})) | |
;; kawa(Scheme) | |
(ExecutorService:submit | |
tp | |
(object (Callable) | |
((call) ::Object 1) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment