Skip to content

Commit 8b86d88

Browse files
committed
Refactor newTopics to remove nested loops
Replace O(n²) nested iteration with O(n) map-based lookups for filtering topics Use topicNameToMapKey to efficiently resolve duplicate topic names This improves application startup time and scalability when managing a large number of topics, while preserving the original filtering logic Resolves: #4025 Signed-off-by: Choi Wang Gyu <[email protected]>
1 parent a7cf43d commit 8b86d88

File tree

1 file changed

+16
-21
lines changed

1 file changed

+16
-21
lines changed

spring-kafka/src/main/java/org/springframework/kafka/core/KafkaAdmin.java

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
* @author Valentina Armenise
8282
* @author Anders Swanson
8383
* @author Omer Celik
84+
* @author Choi Wang Gyu
8485
*
8586
* @since 1.3
8687
*/
@@ -332,31 +333,25 @@ protected Collection<NewTopic> newTopics() {
332333
Map<String, NewTopic> topicsForRetry = newTopicsMap.entrySet().stream()
333334
.filter(entry -> entry.getValue() instanceof TopicForRetryable)
334335
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
336+
Map<String, String> topicNameToMapKey = new HashMap<>();
337+
for (Entry<String, NewTopic> entry : newTopicsMap.entrySet()) {
338+
topicNameToMapKey.put(entry.getValue().name(), entry.getKey());
339+
}
340+
335341
for (Entry<String, NewTopic> entry : topicsForRetry.entrySet()) {
336-
Iterator<Entry<String, NewTopic>> iterator = newTopicsMap.entrySet().iterator();
337-
boolean remove = false;
338-
while (iterator.hasNext()) {
339-
Entry<String, NewTopic> nt = iterator.next();
340-
// if we have a NewTopic and TopicForRetry with the same name, remove the latter
341-
if (nt.getValue().name().equals(entry.getValue().name())
342-
&& !(nt.getValue() instanceof TopicForRetryable)) {
343-
344-
remove = true;
345-
break;
342+
String retryTopicName = entry.getValue().name();
343+
String keyInNewTopicsMap = topicNameToMapKey.get(retryTopicName);
344+
if (keyInNewTopicsMap != null) {
345+
NewTopic existing = newTopicsMap.get(keyInNewTopicsMap);
346+
if (!(existing instanceof TopicForRetryable)) {
347+
newTopicsMap.remove(keyInNewTopicsMap);
346348
}
347349
}
348-
if (remove) {
349-
newTopicsMap.remove(entry.getKey());
350-
}
351350
}
352-
Iterator<Entry<String, NewTopic>> iterator = newTopicsMap.entrySet().iterator();
353-
while (iterator.hasNext()) {
354-
Entry<String, NewTopic> next = iterator.next();
355-
if (!this.createOrModifyTopic.test(next.getValue())) {
356-
iterator.remove();
357-
}
358-
}
359-
return new ArrayList<>(newTopicsMap.values());
351+
Map<String, NewTopic> filteredMap = newTopicsMap.entrySet().stream()
352+
.filter(entry -> this.createOrModifyTopic.test(entry.getValue()))
353+
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
354+
return new ArrayList<>(filteredMap.values());
360355
}
361356

362357
@Override

0 commit comments

Comments
 (0)