Skip to content

Expunge stale entries in InternalLoggerRegistry #3681

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 31, 2025
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core.util.internal;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.message.MessageFactory;
import org.apache.logging.log4j.message.SimpleMessageFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

class InternalLoggerRegistryTest {
private LoggerContext loggerContext;
private InternalLoggerRegistry registry;
private MessageFactory messageFactory;

@BeforeEach
void setUp(TestInfo testInfo) throws NoSuchFieldException, IllegalAccessException {
loggerContext = new LoggerContext(testInfo.getDisplayName());
Field registryField = loggerContext.getClass().getDeclaredField("loggerRegistry");
registryField.setAccessible(true);
registry = (InternalLoggerRegistry) registryField.get(loggerContext);
messageFactory = SimpleMessageFactory.INSTANCE;
}

@AfterEach
void tearDown() {
if (loggerContext != null) {
loggerContext.stop();
}
}

@Test
void testGetLoggerReturnsNullForNonExistentLogger() {
assertNull(registry.getLogger("nonExistent", messageFactory));
}

@Test
void testComputeIfAbsentCreatesLogger() {
Logger logger = registry.computeIfAbsent(
"testLogger", messageFactory, (name, factory) -> new MockLogger(loggerContext, name, factory));
assertNotNull(logger);
assertEquals("testLogger", logger.getName());
}

@Test
void testGetLoggerRetrievesExistingLogger() {
Logger logger = registry.computeIfAbsent(
"testLogger", messageFactory, (name, factory) -> new MockLogger(loggerContext, name, factory));
assertSame(logger, registry.getLogger("testLogger", messageFactory));
}

@Test
void testHasLoggerReturnsCorrectStatus() {
assertFalse(registry.hasLogger("testLogger", messageFactory));
registry.computeIfAbsent(
"testLogger", messageFactory, (name, factory) -> new MockLogger(loggerContext, name, factory));
assertTrue(registry.hasLogger("testLogger", messageFactory));
}

@Test
void testExpungeStaleWeakReferenceEntries() {
String loggerNamePrefix = "testLogger_";
int numberOfLoggers = 1000;

for (int i = 0; i < numberOfLoggers; i++) {
Logger logger = registry.computeIfAbsent(
loggerNamePrefix + i,
messageFactory,
(name, factory) -> new MockLogger(loggerContext, name, factory));
logger.info("Using logger {}", logger.getName());
}

await().atMost(10, SECONDS).pollInterval(100, MILLISECONDS).untilAsserted(() -> {
System.gc();
System.runFinalization();
registry.computeIfAbsent(
"triggerExpunge", messageFactory, (name, factory) -> new MockLogger(loggerContext, name, factory));

Map<MessageFactory, Map<String, WeakReference<Logger>>> loggerRefByNameByMessageFactory =
reflectAndGetLoggerMapFromRegistry();
Map<String, WeakReference<Logger>> loggerRefByName = loggerRefByNameByMessageFactory.get(messageFactory);

boolean isExpungeStaleEntries = true;
for (int i = 0; i < numberOfLoggers; i++) {
if (loggerRefByName.containsKey(loggerNamePrefix + i)) {
isExpungeStaleEntries = false;
break;
}
}
assertTrue(
isExpungeStaleEntries,
"Stale WeakReference entries were not removed from the inner map for MessageFactory");
});
}

@Test
void testExpungeStaleMessageFactoryEntry() {
SimpleMessageFactory mockMessageFactory = new SimpleMessageFactory();
Logger logger = registry.computeIfAbsent(
"testLogger", mockMessageFactory, (name, factory) -> new MockLogger(loggerContext, name, factory));
logger.info("Using logger {}", logger.getName());
logger = null;

await().atMost(10, SECONDS).pollInterval(100, MILLISECONDS).untilAsserted(() -> {
System.gc();
System.runFinalization();
registry.getLogger("triggerExpunge", mockMessageFactory);

Map<MessageFactory, Map<String, WeakReference<Logger>>> loggerRefByNameByMessageFactory =
reflectAndGetLoggerMapFromRegistry();
assertNull(
loggerRefByNameByMessageFactory.get(mockMessageFactory),
"Stale MessageFactory entry was not removed from the outer map");
});
}

@Test
void testConcurrentAccess() throws InterruptedException {
int threadCount = 10;
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
CountDownLatch latch = new CountDownLatch(threadCount);

for (int i = 0; i < threadCount; i++) {
executor.submit(() -> {
registry.computeIfAbsent(
"testLogger", messageFactory, (name, factory) -> new MockLogger(loggerContext, name, factory));
latch.countDown();
});
}

latch.await();
executor.shutdown();

// Verify logger was created and is accessible after concurrent creation
assertNotNull(
registry.getLogger("testLogger", messageFactory),
"Logger should be accessible after concurrent creation");
}

private Map<MessageFactory, Map<String, WeakReference<Logger>>> reflectAndGetLoggerMapFromRegistry()
throws NoSuchFieldException, IllegalAccessException {
Field loggerMapField = registry.getClass().getDeclaredField("loggerRefByNameByMessageFactory");
loggerMapField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<MessageFactory, Map<String, WeakReference<Logger>>> loggerMap =
(Map<MessageFactory, Map<String, WeakReference<Logger>>>) loggerMapField.get(registry);
return loggerMap;
}

private class MockLogger extends Logger {

protected MockLogger(LoggerContext context, String name, MessageFactory messageFactory) {
super(context, name, messageFactory);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@

import static java.util.Objects.requireNonNull;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
Expand All @@ -40,7 +43,9 @@
* A registry of {@link Logger}s namespaced by name and message factory.
* This class is internally used by {@link LoggerContext}.
* <p>
* We don't use {@linkplain org.apache.logging.log4j.spi.LoggerRegistry the registry from Log4j API} to keep Log4j Core independent from the version of Log4j API at runtime.
* We don't use {@linkplain org.apache.logging.log4j.spi.LoggerRegistry the
* registry from Log4j API} to keep Log4j Core independent from the version of
* Log4j API at runtime.
* This also allows Log4j Core to evolve independently from Log4j API.
* </p>
*
Expand All @@ -53,13 +58,43 @@ public final class InternalLoggerRegistry {
new WeakHashMap<>();

private final ReadWriteLock lock = new ReentrantReadWriteLock();

private final Lock readLock = lock.readLock();

private final Lock writeLock = lock.writeLock();

// ReferenceQueue to track stale WeakReferences
private final ReferenceQueue<Logger> staleLoggerRefs = new ReferenceQueue<>();

public InternalLoggerRegistry() {}

/**
* Expunges stale entries for logger references and message factories.
*/
private void expungeStaleEntries() {
Reference<? extends Logger> loggerRef = staleLoggerRefs.poll();

if (loggerRef != null) {
writeLock.lock();
try {
while (staleLoggerRefs.poll() != null) {
// Clear refQueue
}

Iterator<Map.Entry<MessageFactory, Map<String, WeakReference<Logger>>>> outerIt =
loggerRefByNameByMessageFactory.entrySet().iterator();
while (outerIt.hasNext()) {
Map.Entry<MessageFactory, Map<String, WeakReference<Logger>>> outerEntry = outerIt.next();
Map<String, WeakReference<Logger>> innerMap = outerEntry.getValue();
innerMap.values().removeIf(weakRef -> weakRef.get() == null);
if (innerMap.isEmpty()) {
outerIt.remove();
}
}
} finally {
writeLock.unlock();
}
}
}

/**
* Returns the logger associated with the given name and message factory.
*
Expand All @@ -70,6 +105,8 @@ public InternalLoggerRegistry() {}
public @Nullable Logger getLogger(final String name, final MessageFactory messageFactory) {
requireNonNull(name, "name");
requireNonNull(messageFactory, "messageFactory");
expungeStaleEntries(); // Clean up before retrieving

readLock.lock();
try {
final Map<String, WeakReference<Logger>> loggerRefByName =
Expand All @@ -87,6 +124,8 @@ public InternalLoggerRegistry() {}
}

public Collection<Logger> getLoggers() {
expungeStaleEntries(); // Clean up before retrieving

readLock.lock();
try {
// Return a new collection to allow concurrent iteration over the loggers
Expand Down Expand Up @@ -127,6 +166,8 @@ public boolean hasLogger(final String name, final MessageFactory messageFactory)
public boolean hasLogger(final String name, final Class<? extends MessageFactory> messageFactoryClass) {
requireNonNull(name, "name");
requireNonNull(messageFactoryClass, "messageFactoryClass");
expungeStaleEntries(); // Clean up before checking

readLock.lock();
try {
return loggerRefByNameByMessageFactory.entrySet().stream()
Expand All @@ -147,6 +188,8 @@ public Logger computeIfAbsent(
requireNonNull(messageFactory, "messageFactory");
requireNonNull(loggerSupplier, "loggerSupplier");

expungeStaleEntries(); // Clean up before adding a new logger

// Read lock fast path: See if logger already exists
@Nullable Logger logger = getLogger(name, messageFactory);
if (logger != null) {
Expand Down Expand Up @@ -194,9 +237,10 @@ public Logger computeIfAbsent(
if (loggerRefByName == null) {
loggerRefByNameByMessageFactory.put(messageFactory, loggerRefByName = new HashMap<>());
}

final WeakReference<Logger> loggerRef = loggerRefByName.get(name);
if (loggerRef == null || (logger = loggerRef.get()) == null) {
loggerRefByName.put(name, new WeakReference<>(logger = newLogger));
loggerRefByName.put(name, new WeakReference<>(logger = newLogger, staleLoggerRefs));
}
return logger;
} finally {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="https://logging.apache.org/xml/ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
https://logging.apache.org/xml/ns
https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="3430" link="https://github.com/apache/logging-log4j2/issues/3430"/>
<issue id="3681" link="https://github.com/apache/logging-log4j2/pull/3681"/>
<description format="asciidoc">
Improved expunging of stale entries in `InternalLoggerRegistry` to prevent potential memory leaks
</description>
</entry>