-
-
Save jessitron/60d0c1792e0c42b12533 to your computer and use it in GitHub Desktop.
Handy for creating post http://blog.jessitron.com/2014/01/choosing-executorservice.html
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
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