Debian Codegraph @

scala-unit-tests/src/test/scala/org/eclipse/collections/impl/SynchronizedTestTrait.scala

raw
1 /*
2 * Copyright (c) 2021 Goldman Sachs.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * and Eclipse Distribution License v. 1.0 which accompany this distribution.
6 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
7 * and the Eclipse Distribution License is available at
8 * http://www.eclipse.org/org/documents/edl-v10.php.
9 */
10
11 package org.eclipse.collections.impl
12
13 import java.util.concurrent.TimeUnit
14
15 import org.junit.Assert
16
17 trait SynchronizedTestTrait
18 {
19 val classUnderTest: AnyRef
20
21 class Gate
22 {
23 val latch = new java.util.concurrent.CountDownLatch(1)
24
25 def open()
26 {
27 this.latch.countDown()
28 }
29
30 def await()
31 {
32 this.latch.await()
33 }
34 }
35
36 def time(code: => Unit) =
37 {
38 val before = System.currentTimeMillis
39 code
40 val after = System.currentTimeMillis
41 after - before
42 }
43
44 def assertSynchronized(code: => Unit)
45 {
46 this.assertThreadSafety(threadSafe = true, 10L, TimeUnit.MILLISECONDS)(code)
47 }
48
49 def assertNotSynchronized(code: => Unit)
50 {
51 this.assertThreadSafety(threadSafe = false, 60L, TimeUnit.SECONDS)(code)
52 }
53
54 def assertThreadSafety(threadSafe: Boolean, timeout: Long, timeUnit: TimeUnit)(code: => Unit)
55 {
56 def spawn(code: => Unit) =
57 {
58 val result = new Thread
59 {
60 override def run = code
61 }
62 result.start()
63 result
64 }
65
66 val gate = new Gate
67
68 val lockHolderThread = spawn
69 {
70 this.classUnderTest.synchronized
71 {
72 // Don't let the other thread start until we've got the lock
73 gate.open()
74
75 // Hold the lock until interruption
76 try
77 {
78 Thread.sleep(java.lang.Long.MAX_VALUE)
79 }
80 catch
81 {
82 case ignore: InterruptedException => Thread.currentThread.interrupt
83 }
84 }
85 }
86
87 val millisTimeout = TimeUnit.MILLISECONDS.convert(timeout, timeUnit)
88 val measuredTime = time
89 {
90 // Don't start until the other thread is synchronized on classUnderTest
91 gate.await()
92 spawn(code).join(millisTimeout, 0)
93 }
94
95 Assert.assertEquals(
96 "Measured " + measuredTime + " ms but timeout was " + millisTimeout + " ms.",
97 threadSafe,
98 measuredTime >= millisTimeout)
99
100 lockHolderThread.interrupt()
101 lockHolderThread.join()
102 }
103 }