This repository was archived by the owner on Sep 27, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathThrottlerTest.scala
More file actions
103 lines (79 loc) · 2.22 KB
/
Copy pathThrottlerTest.scala
File metadata and controls
103 lines (79 loc) · 2.22 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.komanov.examples
import java.util.concurrent.{CountDownLatch, Executors, Semaphore, TimeUnit}
import org.specs2.mutable.{After, Specification}
import scala.concurrent.{ExecutionContext, Future}
class ThrottlerTest extends Specification {
"Throttler" should {
"execute sequential" in new ctx {
var invocationCount = 0
for (i <- 0 to maxCount) {
throttler {
invocationCount += 1
}
}
invocationCount must be_==(maxCount + 1)
}
"throw exception once reached the limit [naive, flaky]" in new ctx {
for (i <- 1 to maxCount) {
Future {
throttler(waitForever())
}
}
throttler {} must throwA[ThrottledException]
}
"throw exception once reached the limit [naive, bad]" in new ctx {
for (i <- 1 to maxCount) {
Future {
throttler(waitForever())
}
}
Thread.sleep(1000)
throttler {} must throwA[ThrottledException]
}
"throw exception once reached the limit [working]" in new ctx {
val barrier = new CountDownLatch(maxCount)
for (i <- 1 to maxCount) {
Future {
throttler {
barrier.countDown()
waitForever()
}
}
}
barrier.await(5, TimeUnit.SECONDS) must beTrue
throttler {} must throwA[ThrottledException]
}
}
trait ctx extends After {
val maxCount = 3
val throttler = new Throttler(maxCount)
val e = Executors.newCachedThreadPool()
implicit val ec: ExecutionContext = ExecutionContext.fromExecutor(e)
private val waitForeverLatch = new CountDownLatch(1)
override def after: Any = {
waitForeverLatch.countDown()
e.shutdownNow()
}
def waitForever(): Unit = try {
waitForeverLatch.await()
} catch {
case _: InterruptedException =>
case ex: Throwable => throw ex
}
}
}
class ThrottledException extends RuntimeException("Throttled!")
class Throttler(count: Int) {
require(count > 0)
private val semaphore = new Semaphore(count)
def apply(f: => Unit): Unit = {
if (!semaphore.tryAcquire()) {
throw new ThrottledException
}
try {
f
} finally {
semaphore.release()
}
}
}