aboutsummaryrefslogtreecommitdiff
path: root/src/test/scala/scala/async/TestLatch.scala
blob: ece17d1abb985c12b17d476b59aa92b5df83b69d (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
38
39
40
/*
 * Copyright (C) 2012-2014 Lightbend Inc. <http://www.lightbend.com>
 */

package scala.async

import concurrent.{CanAwait, Awaitable}
import concurrent.duration.Duration
import java.util.concurrent.{TimeoutException, CountDownLatch, TimeUnit}

object TestLatch {
  val DefaultTimeout = Duration(5, TimeUnit.SECONDS)

  def apply(count: Int = 1) = new TestLatch(count)
}


class TestLatch(count: Int = 1) extends Awaitable[Unit] {
  private var latch = new CountDownLatch(count)

  def countDown() = latch.countDown()

  def isOpen: Boolean = latch.getCount == 0

  def open() = while (!isOpen) countDown()

  def reset() = latch = new CountDownLatch(count)

  @throws(classOf[TimeoutException])
  def ready(atMost: Duration)(implicit permit: CanAwait) = {
    val opened = latch.await(atMost.toNanos, TimeUnit.NANOSECONDS)
    if (!opened) throw new TimeoutException(s"Timeout of ${(atMost.toString)}.")
    this
  }

  @throws(classOf[Exception])
  def result(atMost: Duration)(implicit permit: CanAwait): Unit = {
    ready(atMost)
  }
}