Skip to content

Commit 8d6f78b

Browse files
committedApr 1, 2025
Fix ArrayList race condition in ConcurrentMessageListenerContainerTests
There is a chance that `ArrayList` may report wrong content when it is used concurrently. * Use `Collections.synchronizedList()` for the `testAutoCommit()` to mitigate memory barrier race condition
1 parent ea6612e commit 8d6f78b

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed
 

Diff for: ‎spring-kafka/src/test/java/org/springframework/kafka/listener/ConcurrentMessageListenerContainerTests.java

+5-2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import java.util.Arrays;
2222
import java.util.BitSet;
2323
import java.util.Collection;
24+
import java.util.Collections;
2425
import java.util.HashSet;
2526
import java.util.Iterator;
2627
import java.util.List;
@@ -148,7 +149,7 @@ protected Consumer<Integer, String> createKafkaConsumer(String groupId, String c
148149

149150
final CountDownLatch latch = new CountDownLatch(3);
150151
final Set<String> listenerThreadNames = new ConcurrentSkipListSet<>();
151-
final List<String> payloads = new ArrayList<>();
152+
List<String> payloads = Collections.synchronizedList(new ArrayList<>());
152153
containerProps.setMessageListener((MessageListener<Integer, String>) message -> {
153154
ConcurrentMessageListenerContainerTests.this.logger.info("auto: " + message);
154155
listenerThreadNames.add(Thread.currentThread().getName());
@@ -198,7 +199,9 @@ protected Consumer<Integer, String> createKafkaConsumer(String groupId, String c
198199
template.flush();
199200
assertThat(intercepted.await(10, TimeUnit.SECONDS)).isTrue();
200201
assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
201-
assertThat(payloads).containsExactlyInAnyOrder("foo", "bar", "qux");
202+
synchronized (payloads) {
203+
assertThat(payloads).containsExactlyInAnyOrder("foo", "bar", "qux");
204+
}
202205
assertThat(listenerThreadNames).contains("testAuto-0", "testAuto-1");
203206
List<KafkaMessageListenerContainer<Integer, String>> containers = KafkaTestUtils.getPropertyValue(container,
204207
"containers", List.class);

0 commit comments

Comments
 (0)