1
+ package com.amplitude.core.platform
2
+
3
+ import com.amplitude.core.Amplitude
4
+ import org.junit.jupiter.api.Assertions.assertTrue
5
+ import org.junit.jupiter.api.Test
6
+ import org.junit.jupiter.api.Timeout
7
+ import java.util.concurrent.CopyOnWriteArrayList
8
+ import java.util.concurrent.Executors
9
+ import java.util.concurrent.TimeUnit
10
+ import kotlin.concurrent.thread
11
+
12
+ class MediatorTest {
13
+ private val mediator = Mediator (CopyOnWriteArrayList ())
14
+
15
+ /* *
16
+ * Fake [DestinationPlugin] that does work on [flush] for 1 second
17
+ */
18
+ private class FakeDestinationPlugin : DestinationPlugin () {
19
+ var workDone = false
20
+
21
+ override fun flush () {
22
+ super .flush()
23
+ println (" $this start work ${System .currentTimeMillis()} ${Thread .currentThread().name} " )
24
+ Thread .sleep(1_000 )
25
+ println (" $this end work ${System .currentTimeMillis()} ${Thread .currentThread().name} " )
26
+ workDone = true
27
+ }
28
+ }
29
+
30
+ @Test
31
+ @Timeout(2 , unit = TimeUnit .SECONDS )
32
+ fun `multiple threads that call flush on destination plugin` () {
33
+ val fakeDestinationPlugins = List (10 ) { FakeDestinationPlugin () }
34
+ fakeDestinationPlugins.forEach {
35
+ mediator.add(it)
36
+ }
37
+
38
+ // simulate 10 threads executing flush on 10 different [DestinationPlugin]s
39
+ val executor = Executors .newFixedThreadPool(10 )
40
+ fakeDestinationPlugins.forEach {
41
+ executor.submit {
42
+ it.flush()
43
+ }
44
+ }
45
+ executor.shutdown()
46
+ executor.awaitTermination(2 , TimeUnit .SECONDS )
47
+
48
+ assertTrue {
49
+ fakeDestinationPlugins.all { it.workDone }
50
+ }
51
+ }
52
+
53
+ @Test
54
+ @Timeout(2 , unit = TimeUnit .SECONDS )
55
+ fun `two threads that call flush on destination plugin` () {
56
+ val fakeDestinationPlugins = List (2 ) { FakeDestinationPlugin () }
57
+ fakeDestinationPlugins.forEach {
58
+ mediator.add(it)
59
+ }
60
+
61
+ // simulate 2 threads executing flush on 2 different DestinationPlugins
62
+ val t1 = thread {
63
+ fakeDestinationPlugins[0 ].flush()
64
+ }
65
+ val t2 = thread {
66
+ fakeDestinationPlugins[1 ].flush()
67
+ }
68
+ t1.join()
69
+ t2.join()
70
+
71
+ assertTrue {
72
+ fakeDestinationPlugins.all { it.workDone }
73
+ }
74
+ }
75
+
76
+ }
0 commit comments