summaryrefslogtreecommitdiff
path: root/cask/src/cask/internal/BatchActor.scala
blob: 1566a1872f2e3a3ee5ea9945fe345d795664452e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package cask.internal

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) {
  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 => e.printStackTrace()}
    synchronized{
      if (queue.nonEmpty) ec.execute(() => runWithItems())
      else{
        assert(scheduled)
        scheduled = false
      }
    }

  }
}