Skip to content

Commit b4ef5dd

Browse files
authored
Improve performance of CloseableThreadContext#closeMap() (#2292, #2296)
1 parent 8edb133 commit b4ef5dd

File tree

2 files changed

+20
-8
lines changed

2 files changed

+20
-8
lines changed

log4j-api/src/main/java/org/apache/logging/log4j/CloseableThreadContext.java

+12-8
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@
1616
*/
1717
package org.apache.logging.log4j;
1818

19+
import java.util.ArrayList;
1920
import java.util.HashMap;
20-
import java.util.Iterator;
2121
import java.util.List;
2222
import java.util.Map;
2323

@@ -203,18 +203,22 @@ public void close() {
203203
}
204204

205205
private void closeMap() {
206-
for (final Iterator<Map.Entry<String, String>> it =
207-
originalValues.entrySet().iterator();
208-
it.hasNext(); ) {
209-
final Map.Entry<String, String> entry = it.next();
206+
final Map<String, String> valuesToReplace = new HashMap<>(originalValues.size());
207+
final List<String> keysToRemove = new ArrayList<>(originalValues.size());
208+
for (final Map.Entry<String, String> entry : originalValues.entrySet()) {
210209
final String key = entry.getKey();
211210
final String originalValue = entry.getValue();
212211
if (null == originalValue) {
213-
ThreadContext.remove(key);
212+
keysToRemove.add(key);
214213
} else {
215-
ThreadContext.put(key, originalValue);
214+
valuesToReplace.put(key, originalValue);
216215
}
217-
it.remove();
216+
}
217+
if (!valuesToReplace.isEmpty()) {
218+
ThreadContext.putAll(valuesToReplace);
219+
}
220+
if (!keysToRemove.isEmpty()) {
221+
ThreadContext.removeAll(keysToRemove);
218222
}
219223
}
220224

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xmlns="http://logging.apache.org/log4j/changelog"
4+
xsi:schemaLocation="http://logging.apache.org/log4j/changelog https://logging.apache.org/log4j/changelog-0.1.3.xsd"
5+
type="changed">
6+
<issue id="2296" link="https://github.com/apache/logging-log4j2/pull/2296"/>
7+
<description format="asciidoc">Improve performance of `CloseableThreadContext#closeMap()`</description>
8+
</entry>

0 commit comments

Comments
 (0)