im.yagni.driveby.pool.BrowserPool.scala Maven / Gradle / Ivy
The newest version!
package im.yagni.driveby.pool
import im.yagni.driveby.browser.Browser
import im.yagni.common.OnShutdown
import im.yagni.driveby.tracking._
import im.yagni.driveby.{Example, BrowserFactory}
import collection.mutable.ListBuffer
import actors.threadpool.LinkedBlockingQueue
object BrowserPool {
private val allBrowsers = new ListBuffer[Browser]
private val availableBrowsers = new LinkedBlockingQueue[Browser]
def add(browser: String, instances: Int = 1) {
times(instances) { add(BrowserFactory.create(browser)) }
}
def write(browser: Browser, example: Example) {
Tracker.add(BrowserWritten(example.id, browser.id))
availableBrowsers.put(browser)
}
def take(example: Example) = {
Tracker.add(BrowserTakeRequested(example.id))
val browser = availableBrowsers.take()
Tracker.add(BrowserTaken(example.id, browser.id))
browser
}
private def add(browser: Browser) {
allBrowsers.append(browser)
availableBrowsers.put(browser)
}
private def times(n: Int) (code: => Unit) {
for (i <- 1 to n) code
}
OnShutdown.execute("Close browsers", () =>
allBrowsers.map(browser => {
try {
browser.close()
Tracker.add(BrowserClosed(browser.id))
} catch {
case e => Tracker.add(BrowserCloseFailed(browser.id))
}
}))
}