summaryrefslogtreecommitdiff
path: root/cask/src/cask/util/BatchActor.scala
diff options
context:
space:
mode:
authorLi Haoyi <haoyi.sg@gmail.com>2019-09-15 13:20:44 +0800
committerLi Haoyi <haoyi.sg@gmail.com>2019-09-15 13:20:44 +0800
commit60a23d3250db88f6147adf4e74f7497f870cd2ec (patch)
tree205578814e777c277985f44ee92b7ec9e194b7b9 /cask/src/cask/util/BatchActor.scala
parentf158811a79f702a406e3dd2b961f3b085e6c47c0 (diff)
downloadcask-60a23d3250db88f6147adf4e74f7497f870cd2ec.tar.gz
cask-60a23d3250db88f6147adf4e74f7497f870cd2ec.tar.bz2
cask-60a23d3250db88f6147adf4e74f7497f870cd2ec.zip
Move `internal.BatchActor` to `util.BatchActor`
Diffstat (limited to 'cask/src/cask/util/BatchActor.scala')
-rw-r--r--cask/src/cask/util/BatchActor.scala40
1 files changed, 40 insertions, 0 deletions
diff --git a/cask/src/cask/util/BatchActor.scala b/cask/src/cask/util/BatchActor.scala
new file mode 100644
index 0000000..137b852
--- /dev/null
+++ b/cask/src/cask/util/BatchActor.scala
@@ -0,0 +1,40 @@
+package cask.util
+
+import cask.util.Logger
+
+import scala.collection.mutable
+import scala.concurrent.ExecutionContext
+
+/**
+ * A simple asynchrous actor, allowing safe concurrent asynchronous processing
+ * of queued items. `run` handles items in batches, to allow for batch
+ * processing optimizations to be used where relevant.
+ */
+abstract class BatchActor[T]()(implicit ec: ExecutionContext,
+ log: Logger) {
+ def run(items: Seq[T]): Unit
+
+ private val queue = new mutable.Queue[T]()
+ private var scheduled = false
+ def send(t: => T): Unit = synchronized{
+ queue.enqueue(t)
+ if (!scheduled){
+ scheduled = true
+ ec.execute(() => runWithItems())
+ }
+ }
+
+ def runWithItems(): Unit = {
+ val items = synchronized(queue.dequeueAll(_ => true))
+ try run(items)
+ catch{case e: Throwable => log.exception(e)}
+ synchronized{
+ if (queue.nonEmpty) ec.execute(() => runWithItems())
+ else{
+ assert(scheduled)
+ scheduled = false
+ }
+ }
+
+ }
+}