Skip to content

Instantly share code, notes, and snippets.

@heuristicfencepost
Created January 7, 2011 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heuristicfencepost/769168 to your computer and use it in GitHub Desktop.
Save heuristicfencepost/769168 to your computer and use it in GitHub Desktop.
Samples of SAM handling in JRuby and Scala
require 'java'
queue = java.util.concurrent.LinkedBlockingQueue.new()
exec = java.util.concurrent.ThreadPoolExecutor.new(2,2,1,java.util.concurrent.TimeUnit::SECONDS,queue)
exec.prestartAllCoreThreads
# Use a closure that does some kind of computation rather than just returning a value.
# As always last expression in the closure is the return value.
future = exec.submit do
arr = []
1.upto(5) { |val| arr.push(2 * val) }
arr
end
exec.shutdown
rv = future.get
if rv.length == 5 && (rv.include? 2) && (rv.include? 6)
print "Good\n"
else
print "Not good\n"
end
package org.fencepost
import scala.collection.mutable._
import org.scalatest.Suite
import java.util.concurrent._
class SAMTest extends Suite {
implicit def fn2runnable(fn:()=>Unit):Runnable = {
new Runnable { def run = fn.apply }
}
implicit def fn2callable[A](fn:()=>A):Callable[A] = {
new Callable[A] { def call = fn.apply }
}
// We can now use a closure as a replacement for a Runnable instance
def testClosureAsRunnable() = {
var result = ListBuffer(1,2,3)
val t = new Thread({ () =>
result += 4
// Addition of new item to the list buffer returns the item added so
// leaving it as the last expression would violate our ()=>Unit type.
// A simple println solves this.
println("Done")
})
t.start
t.join
assert(result.size == 4)
assert(result.contains(4))
}
// Verify that parameterized types are supported as well while demonstrating
// integration with java.util.concurrent. We deliberately avoid references
// to scala.concurrent in order to avoid confusing the issue.
def testClosureAsParameterizedSAM() = {
val exec = new ThreadPoolExecutor(2,2,1,TimeUnit.SECONDS,new LinkedBlockingQueue())
exec.prestartAllCoreThreads
val future = exec.submit({ ()=> List(1,2,3).map(_ * 2) })
val result = future.get
exec.shutdown
assert(result.size == 3)
assert(result.contains(2))
assert(result.contains(4))
assert(result.contains(6))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment