Skip to content

Commit 53ce1f6

Browse files
fix(datastructures): correct test capacity and simplify concurrent test
- testOfferPoll: Changed capacity from 3 to 2 so third offer correctly fails - testMultipleProducersSingleConsumer: Removed startLatch, use dedicated consumer thread with synchronized results list for thread safety
1 parent 8990d50 commit 53ce1f6

1 file changed

Lines changed: 11 additions & 10 deletions

File tree

src/test/java/com/thealgorithms/datastructures/queues/ThreadSafeQueueTest.java

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public void testEnqueueDequeue() throws InterruptedException {
3434

3535
@Test
3636
public void testOfferPoll() {
37-
ThreadSafeQueue<String> queue = new ThreadSafeQueue<>(3);
37+
ThreadSafeQueue<String> queue = new ThreadSafeQueue<>(2);
3838
assertTrue(queue.offer("a"));
3939
assertTrue(queue.offer("b"));
4040
assertFalse(queue.offer("c"));
@@ -130,7 +130,6 @@ public void testMultipleProducersSingleConsumer() throws InterruptedException {
130130
int numProducers = 4;
131131
int itemsPerProducer = 250;
132132
int totalItems = numProducers * itemsPerProducer;
133-
CountDownLatch startLatch = new CountDownLatch(1);
134133
CountDownLatch doneLatch = new CountDownLatch(numProducers);
135134
List<Integer> results = new ArrayList<>();
136135

@@ -140,7 +139,6 @@ public void testMultipleProducersSingleConsumer() throws InterruptedException {
140139
final int producerId = p;
141140
executor.submit(() -> {
142141
try {
143-
startLatch.await();
144142
for (int i = 0; i < itemsPerProducer; i++) {
145143
queue.enqueue(producerId * itemsPerProducer + i);
146144
}
@@ -152,25 +150,28 @@ public void testMultipleProducersSingleConsumer() throws InterruptedException {
152150
});
153151
}
154152

155-
executor.submit(() -> {
153+
Thread consumerThread = new Thread(() -> {
156154
try {
157-
doneLatch.await();
158155
while (results.size() < totalItems) {
159156
Integer item = queue.poll();
160157
if (item != null) {
161-
results.add(item);
158+
synchronized (results) {
159+
results.add(item);
160+
}
162161
}
163162
}
164-
} catch (InterruptedException e) {
163+
} catch (Exception e) {
165164
Thread.currentThread().interrupt();
166165
}
167166
});
167+
consumerThread.start();
168168

169-
startLatch.countDown();
170-
executor.shutdown();
171-
assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
169+
assertTrue(doneLatch.await(10, TimeUnit.SECONDS));
170+
consumerThread.join(5000);
172171

173172
assertEquals(totalItems, results.size());
173+
executor.shutdown();
174+
assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
174175
}
175176

176177
@Test

0 commit comments

Comments
 (0)