-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLeaderFollowerPatternTest.java
More file actions
376 lines (305 loc) · 14.3 KB
/
LeaderFollowerPatternTest.java
File metadata and controls
376 lines (305 loc) · 14.3 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package org.alxkm.patterns.leaderfollower;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Set;
public class LeaderFollowerPatternTest {
private LeaderFollowerPattern<LeaderFollowerPattern.Event> leaderFollower;
private AtomicInteger processedEventCount;
private Set<String> processingThreads;
private AtomicBoolean processingError;
//@BeforeEach
public void setUp() {
processedEventCount = new AtomicInteger(0);
processingThreads = ConcurrentHashMap.newKeySet();
processingError = new AtomicBoolean(false);
leaderFollower = new LeaderFollowerPattern<>(4, event -> {
try {
// Record the processing thread
processingThreads.add(Thread.currentThread().getName());
// Simulate processing
Thread.sleep(10);
processedEventCount.incrementAndGet();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
processingError.set(true);
} catch (Exception e) {
processingError.set(true);
}
});
}
//@AfterEach
public void tearDown() {
if (leaderFollower != null && leaderFollower.isRunning()) {
leaderFollower.shutdown();
}
}
//@Test
public void testBasicStartupAndShutdown() {
assertFalse(leaderFollower.isRunning());
assertEquals(0, leaderFollower.getActiveThreadCount());
leaderFollower.start();
assertTrue(leaderFollower.isRunning());
// Wait for threads to initialize
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
assertEquals(4, leaderFollower.getActiveThreadCount());
leaderFollower.shutdown();
assertFalse(leaderFollower.isRunning());
// Wait for threads to finish
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 0, 2000);
assertEquals(0, leaderFollower.getActiveThreadCount());
}
//@Test
public void testEventProcessing() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
// Submit some events
for (int i = 0; i < 10; i++) {
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(i, "Test data " + i);
assertTrue(leaderFollower.submitEvent(event));
}
// Wait for processing to complete
waitForCondition(() -> leaderFollower.getProcessedEventCount() == 10, 5000);
assertEquals(10, processedEventCount.get());
assertEquals(10, leaderFollower.getProcessedEventCount());
assertFalse(processingError.get());
}
//@Test
public void testLeaderPromotion() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
int initialPromotions = leaderFollower.getLeaderPromotionCount();
// Submit events to trigger leader promotions
for (int i = 0; i < 5; i++) {
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(i, "Test data " + i);
leaderFollower.submitEvent(event);
}
// Wait for processing
waitForCondition(() -> leaderFollower.getProcessedEventCount() == 5, 3000);
// Should have had leader promotions
assertTrue(leaderFollower.getLeaderPromotionCount() > initialPromotions);
}
//@Test
public void testConcurrentEventSubmission() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
final int threadCount = 5;
final int eventsPerThread = 10;
final CountDownLatch latch = new CountDownLatch(threadCount);
final AtomicInteger submittedCount = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
final int threadId = i;
executor.submit(() -> {
try {
for (int j = 0; j < eventsPerThread; j++) {
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(
threadId * 100 + j,
"Data from thread " + threadId
);
if (leaderFollower.submitEvent(event)) {
submittedCount.incrementAndGet();
}
}
} finally {
latch.countDown();
}
});
}
assertTrue(latch.await(5, TimeUnit.SECONDS));
// Wait for all events to be processed
final int expectedEvents = threadCount * eventsPerThread;
waitForCondition(() -> leaderFollower.getProcessedEventCount() == expectedEvents, 10000);
assertEquals(expectedEvents, submittedCount.get());
assertEquals(expectedEvents, leaderFollower.getProcessedEventCount());
assertFalse(processingError.get());
executor.shutdown();
assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
}
//@Test
public void testMultipleThreadsProcessing() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
// Submit enough events to ensure multiple threads get to process
for (int i = 0; i < 20; i++) {
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(i, "Test data " + i);
leaderFollower.submitEvent(event);
}
// Wait for processing
waitForCondition(() -> leaderFollower.getProcessedEventCount() == 20, 10000);
// Multiple threads should have participated in processing
assertTrue(processingThreads.size() > 1,
"Expected multiple threads to process events, but only " + processingThreads.size() + " threads were used");
assertFalse(processingError.get());
}
//@Test
public void testBlockingEventSubmission() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(1, "Blocking test");
// This should not block since the queue is not full
leaderFollower.submitEventBlocking(event);
waitForCondition(() -> leaderFollower.getProcessedEventCount() == 1, 2000);
assertEquals(1, leaderFollower.getProcessedEventCount());
}
//@Test
public void testSubmissionToShutdownPool() {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
leaderFollower.shutdown();
waitForCondition(() -> !leaderFollower.isRunning(), 2000);
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(1, "Test after shutdown");
assertFalse(leaderFollower.submitEvent(event));
assertThrows(IllegalStateException.class, () -> {
leaderFollower.submitEventBlocking(event);
});
}
//@Test
public void testShutdownNow() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
// Submit events
for (int i = 0; i < 10; i++) {
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(i, "Test data " + i);
leaderFollower.submitEvent(event);
}
// Immediate shutdown
leaderFollower.shutdownNow();
assertFalse(leaderFollower.isRunning());
assertEquals(0, leaderFollower.getPendingEventCount()); // Queue should be cleared
}
//@Test
public void testStatistics() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
assertEquals(4, leaderFollower.getActiveThreadCount());
assertEquals(0, leaderFollower.getPendingEventCount());
assertEquals(0, leaderFollower.getProcessedEventCount());
assertTrue(leaderFollower.getLeaderPromotionCount() > 0); // Initial leader selection
// Submit events
for (int i = 0; i < 5; i++) {
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(i, "Test data " + i);
leaderFollower.submitEvent(event);
}
// Wait for processing
waitForCondition(() -> leaderFollower.getProcessedEventCount() == 5, 3000);
assertEquals(5, leaderFollower.getProcessedEventCount());
assertTrue(leaderFollower.getLeaderPromotionCount() >= 1); // Should have at least initial promotion
}
//@Test
public void testCurrentLeader() throws InterruptedException {
leaderFollower.start();
waitForCondition(() -> leaderFollower.getActiveThreadCount() == 4, 2000);
// Initially there should be a leader
waitForCondition(() -> leaderFollower.getCurrentLeader() != null, 1000);
assertNotNull(leaderFollower.getCurrentLeader());
// Submit an event to trigger leader change
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(1, "Leader test");
leaderFollower.submitEvent(event);
// Wait for processing
waitForCondition(() -> leaderFollower.getProcessedEventCount() == 1, 2000);
// There should still be a leader (new one promoted)
Thread.sleep(100); // Brief wait for leader promotion
assertNotNull(leaderFollower.getCurrentLeader());
}
//@Test
public void testConstructorValidation() {
assertThrows(IllegalArgumentException.class, () -> {
new LeaderFollowerPattern<>(0, event -> {});
});
assertThrows(IllegalArgumentException.class, () -> {
new LeaderFollowerPattern<>(-1, event -> {});
});
assertThrows(IllegalArgumentException.class, () -> {
new LeaderFollowerPattern<>(4, null);
});
}
//
public void testEventClass() {
LeaderFollowerPattern.Event event = new LeaderFollowerPattern.Event(42, "Test data");
assertEquals(42, event.getId());
assertEquals("Test data", event.getData());
assertTrue(event.getTimestamp() > 0);
assertNotNull(event.toString());
assertTrue(event.toString().contains("42"));
assertTrue(event.toString().contains("Test data"));
}
//@Test
public void testStressTest() throws InterruptedException {
final int eventCount = 50; // Reduced from 100
final AtomicInteger errorCount = new AtomicInteger(0);
LeaderFollowerPattern<LeaderFollowerPattern.Event> stressTestPool =
new LeaderFollowerPattern<>(4, event -> { // Reduced from 6
try {
// Simulate variable processing time
Thread.sleep(1 + (event.getId() % 3)); // Reduced from % 5
processedEventCount.incrementAndGet();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
errorCount.incrementAndGet();
} catch (Exception e) {
errorCount.incrementAndGet();
}
});
try {
stressTestPool.start();
waitForCondition(() -> stressTestPool.getActiveThreadCount() == 4, 2000);
// Submit events rapidly from multiple threads
ExecutorService executor = Executors.newFixedThreadPool(4);
CountDownLatch submissionLatch = new CountDownLatch(4);
for (int i = 0; i < 4; i++) {
final int startId = i * 12; // Adjusted for 50 total events
int finalI = i;
executor.submit(() -> {
try {
for (int j = 0; j < 12 + (finalI == 0 ? 2 : 0); j++) { // First thread does 14, others do 12
LeaderFollowerPattern.Event event =
new LeaderFollowerPattern.Event(startId + j, "Stress test data");
stressTestPool.submitEvent(event);
}
} finally {
submissionLatch.countDown();
}
});
}
assertTrue(submissionLatch.await(5, TimeUnit.SECONDS));
// Wait for processing to complete
waitForCondition(() -> stressTestPool.getProcessedEventCount() == eventCount, 15000);
assertEquals(eventCount, stressTestPool.getProcessedEventCount());
assertEquals(0, errorCount.get());
assertTrue(stressTestPool.getLeaderPromotionCount() > 4); // Should have many promotions
executor.shutdown();
assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
} finally {
stressTestPool.shutdown();
}
}
/**
* Utility method to wait for a condition with timeout.
*/
private void waitForCondition(java.util.concurrent.Callable<Boolean> condition, long timeoutMs) {
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < timeoutMs) {
try {
if (condition.call()) {
return;
}
Thread.sleep(10);
} catch (Exception e) {
// Ignore and continue waiting
}
}
}
}