Skip to content

Instantly share code, notes, and snippets.

@jessitron
Created January 30, 2014 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jessitron/60d0c1792e0c42b12533 to your computer and use it in GitHub Desktop.
Save jessitron/60d0c1792e0c42b12533 to your computer and use it in GitHub Desktop.
import java.util.concurrent._
def now:Long = (new java.util.Date).getTime
import scala.concurrent.duration._
class Timer {
val then = now
def stop: Duration = (now - then).millis
override def toString = (s"Timer started $stop ago")
}
def sleep(d: Duration) { Thread.sleep(d.toMillis)}
def tc = Thread.currentThread.getName
def sayHiInTwoSec:Runnable = {
val t = new Timer
val snooze:Duration = 2.seconds
new Runnable {
def run {
sleep(snooze)
println(s"Hi from $tc after sleeping $snooze, delay of ${t.stop - snooze}")
}
}
}
def submitN(pool: ExecutorService, n: Int) {
for (_ <- 1 to n) {
pool.execute(sayHiInTwoSec)
}
}
def poolStats(es: ExecutorService) = es match {
case tpe: ThreadPoolExecutor =>
println(s"Core Pool Size: ${tpe.getCorePoolSize}")
println(s"Max Pool Size: ${tpe.getMaximumPoolSize}")
println(s"Queue Capacity: ${tpe.getQueue.remainingCapacity + tpe.getQueue.size}")
println(s"Running Threads: ${tpe.getPoolSize}")
println(s"Active Threads: ${tpe.getActiveCount}")
println(s"Waiting Tasks : ${tpe.getQueue.size}")
case _ => "Sorry, I can't dig around in a " + es.getClass.getName
}
poolStats(Executors.newCachedThreadPool)
//Core Pool Size: 0
//Max Pool Size: 2147483647
//Queue Capacity: 0
//Running Threads: 0
//Active Threads: 0
//Waiting Tasks : 0
poolStats(Executors.newFixedThreadPool(2))
//Core Pool Size: 2
//Max Pool Size: 2
//Queue Capacity: 2147483647
//Running Threads: 0
//Active Threads: 0
//Waiting Tasks : 0
val coreOfThree = new ThreadPoolExecutor(3,6,10, TimeUnit.SECONDS, new ArrayBlockingQueue(4))
coreOfThree.execute(sayHiInTwoSec); poolStats(coreOfThree)
val shortQ = new ThreadPoolExecutor(1, 2, 10, TimeUnit.SECONDS, new ArrayBlockingQueue[Runnable](2))
submitN(shortQ, 5); poolStats(shortQ) // RejectedExecutionException
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment