Skip to content

Async loggers silently discard events when the ring buffer is full and LMAX Disruptor 4 is used #4356

Open

Description

@plusterkopp

Title: Async loggers silently discard events when the ring buffer is full and LMAX Disruptor 4 is used

Description

When AsyncLoggerContextSelector is combined with LMAX Disruptor 4.0.0, log events are dropped without any trace once the ring buffer runs full. In our server, a burst of warnings at start-up (about 180k events in under 2 s from 16 threads) made single lines of unrelated threads and appenders disappear. The standalone reproducer below loses 56–82% of its events. Nothing is written to the StatusLogger (tested with status="WARN") or to stderr.

Cause

Disruptor 4.0.0 changed MultiProducerSequencer.next() to claim a sequence first and wait for free capacity afterwards:

long current = cursor.getAndAdd(n);           // claims before capacity is available
long nextSequence = current + n;
long wrapPoint = nextSequence - bufferSize;
...
while (wrapPoint > (gatingSequence = Util.getMinimumSequence(gatingSequences, current))) {
    LockSupport.parkNanos(1L);
}

While one thread waits in that loop, the cursor is ahead of the consumer by more than the buffer size. remainingCapacity() (bufferSize - (produced - consumed)) therefore returns a negative value, typically -1. Disruptor 3.x next() only advances the cursor with a CAS after capacity is available, so this never happens there.

AsyncLoggerDisruptor.getEventRoute() treats any negative capacity as "log4j has been shut down":

EventRoute getEventRoute(final Level logLevel) {
    final int remainingCapacity = remainingDisruptorCapacity();
    if (remainingCapacity < 0) {
        return EventRoute.DISCARD;
    }
    return asyncQueueFullPolicy.getRoute(backgroundThreadId, logLevel);
}

remainingDisruptorCapacity() returns -1 only when disruptor == null, but it also passes through negative values from RingBuffer.remainingCapacity(). The sequence when the ring buffer is full:

  1. Thread A's tryPublish fails, getEventRoute() returns ENQUEUE, and A enters enqueueLogMessageWhenQueueFull → publishEvent → next(). There it claims a slot beyond the buffer and parks.
  2. Every other thread whose tryPublish fails now sees remainingCapacity() == -1. It gets DISCARD, and handleRingBufferFull clears the translator without a message.

Under sustained saturation effectively only the thread holding queueFullEnqueueLock gets its events in; all others lose theirs. The configured AsyncQueueFullPolicy is never consulted, because the DISCARD decision is made before it. log4j2.asyncLoggerSynchronizeEnqueueWhenQueueFull=false makes it worse, since more threads wait inside next() at the same time.

AsyncLoggerConfigDisruptor.getEventRoute() has the same check, so mixed async loggers (<AsyncLogger>) should be affected too; we have only tested AsyncLoggerContextSelector. The check is unchanged on the current 2.x branch.

A much rarer variant exists with Disruptor 3.x as well. remainingCapacity() reads consumed and produced separately. If the consumer advances between the two reads and producers immediately claim the freed slots, the result is briefly negative. We observed -51, one progress step of RingBufferLogEventHandler, when polling it while the buffer was full. We never saw an event lost this way, but the same check would discard it.

Suggested fix

Check for shutdown explicitly instead of inferring it from the capacity. In AsyncLoggerDisruptor (and likewise in AsyncLoggerConfigDisruptor):

EventRoute getEventRoute(final Level logLevel) {
    if (hasLog4jBeenShutDown(disruptor)) {
        return EventRoute.DISCARD;
    }
    return asyncQueueFullPolicy.getRoute(backgroundThreadId, logLevel);
}

With this change the reproducer below loses no events with Disruptor 4.0.0 (3 of 3 runs, 800,000 of 800,000 lines).

Configuration

Version: log4j 2.25.3. 2.24.3 and 2.25.2 behave the same with Disruptor 4.0.0. Disruptor 3.4.1 does not show the loss with any of them.

Operating system: Windows 11, 8 logical CPUs

JDK: Eclipse Temurin 25.0.3+9

Logs

Nothing is logged, and that is the core of the problem. With status="WARN", the StatusLogger stays silent and nothing appears on stderr.

Reproduction

Single-file program, run with Java 17+ in source-file mode. It uses the default ring buffer size, which is 4096 in garbage-free mode:

java -cp log4j-api-2.25.3.jar:log4j-core-2.25.3.jar:disruptor-4.0.0.jar Log4jDisruptor4Loss.java
Log4jDisruptor4Loss.java
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4jDisruptor4Loss {

    static final int THREADS = 16;
    static final int LINES = 50_000;

    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("log4j-loss");
        Path log = dir.resolve("test.log");
        Path config = dir.resolve("log4j2.xml");
        Files.writeString(config, """
                <Configuration status="WARN">
                  <Appenders>
                    <File name="file" fileName="%s">
                      <PatternLayout pattern="%%d %%-5p [%%t] %%c - %%m%%n"/>
                    </File>
                  </Appenders>
                  <Loggers>
                    <Root level="INFO"><AppenderRef ref="file"/></Root>
                  </Loggers>
                </Configuration>
                """.formatted(log.toAbsolutePath().toString().replace('\\', '/')));
        System.setProperty("log4j2.contextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        System.setProperty("log4j2.configurationFile", config.toUri().toString());

        Logger logger = LogManager.getLogger("test");
        CountDownLatch start = new CountDownLatch(1);
        List<Thread> threads = new ArrayList<>();
        for (int t = 0; t < THREADS; t++) {
            int thread = t;
            Thread th = new Thread(() -> {
                try {
                    start.await();
                } catch (InterruptedException e) {
                    return;
                }
                for (int i = 0; i < LINES; i++) {
                    logger.info("LINE {} {} padding padding padding padding padding padding padding padding", thread, i);
                }
            }, "producer-" + t);
            th.start();
            threads.add(th);
        }
        long startNanos = System.nanoTime();
        start.countDown();
        for (Thread th : threads) {
            th.join();
        }
        long producedMs = (System.nanoTime() - startNanos) / 1_000_000;
        // stops the disruptor after draining it and closes the file
        LogManager.shutdown();

        BitSet[] seen = new BitSet[THREADS];
        for (int t = 0; t < THREADS; t++) {
            seen[t] = new BitSet(LINES);
        }
        for (String line : Files.readAllLines(log, StandardCharsets.UTF_8)) {
            int at = line.indexOf(" - LINE ");
            if (at < 0) {
                continue;
            }
            String[] fields = line.substring(at + 8).split(" ", 3);
            seen[Integer.parseInt(fields[0])].set(Integer.parseInt(fields[1]));
        }
        long expected = (long) THREADS * LINES;
        long found = 0;
        for (BitSet bits : seen) {
            found += bits.cardinality();
        }
        String disruptor = com.lmax.disruptor.RingBuffer.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        System.out.printf("Disruptor %s: %d threads logged %d lines in %d ms, %d in the file, %d missing (%.1f%%)%n",
                disruptor.substring(disruptor.lastIndexOf('/') + 1), THREADS, expected, producedMs, found,
                expected - found, 100.0 * (expected - found) / expected);
    }
}

Results, 3 runs each:

Setup Missing lines
log4j 2.25.3 + Disruptor 4.0.0 81.7%, 56.4%, 68.1%
log4j 2.25.3 + Disruptor 3.4.1 0, 0, 0
log4j 2.25.3 + Disruptor 4.0.0 + suggested fix 0, 0, 0

In a larger test with 16 flooding threads plus low-rate probe threads, repeated rounds and several appenders, we saw the same picture:

  • Disruptor 4.0.0 lost 50–97% with log4j 2.24.3, 2.25.2 and 2.25.3.
  • Disruptor 3.4.1 lost nothing in about 30 million lines under constant saturation.
  • A ring buffer large enough never to fill (4M) also avoids the loss, but only because the queue-full path is never taken.

Log4jDisruptor4Loss.java

AsyncLoggerDisruptor.java

Activity

  1. plusterkopp commented on Sep 25, 2026

    @plusterkopp
    Author

    My finding, but not my words, not my investigation and not my fix. Greetings to Claude Opus 5.5.

  2. added
    bug
    java
    async
    and removed on Sep 26, 2026
  3. added this to the 2.27.0 milestone on Sep 26, 2026
  4. ramanathan1504 commented on Sep 26, 2026

    @ramanathan1504
    Contributor

    @plusterkopp

    Thanks for the clear report and the reproducer. I ran it here and see the same loss with Disruptor 4 on 2.25.3, 2.26.1 and 2.x, and none with Disruptor 3.

    I opened #4357 with a fix. getEventRoute now checks for shutdown directly instead of using a negative capacity. With it, your program loses no lines on Disruptor 4.

    Could you try the PR build in your server and confirm the loss is gone? You can build it with ./mvnw install -pl log4j-core -am -DskipTests on the PR branch and use
    2.27.0-SNAPSHOT.

  5. plusterkopp commented on Sep 27, 2026

    @plusterkopp
    Author

    Well, the loss was already gone in the fix and test I submitted.
    But after checking out and with

    git status

    On branch fix/4356-disruptor4-discard
    Your branch is up to date with 'origin/fix/4356-disruptor4-discard'.
    nothing to commit, working tree clean

    and then I get after

    JAVA_HOME=$HOME/soft/jdks/jdk-17 ./mvnw install -pl log4j-core -am -DskipTests

    [ERROR] Failed to execute goal org.apache.maven.plugins:maven-dependency-plugin:3.8.1:unpack (unpack-classes) on project log4j-api: Unable to find/resolve artifact.: The following artifacts could not be resolved: org.apache.logging.log4j:log4j-api-java9:zip:2.27.0-SNAPSHOT (absent): Could not find artifact org.apache.logging.log4j:log4j-api-java9:zip:2.27.0-SNAPSHOT -> [Help 1]

  6. ramanathan1504 commented on Sep 28, 2026

    @ramanathan1504
    Contributor

    Sorry 🙏, the command I gave you was wrong. Thanks for trying it and reporting back.

    This one builds the PR branch from a fresh clone and an empty Maven repository:

    ./mvnw install -pl :log4j-api-java9,:log4j-core-java9,:log4j-core -am -DskipTests

    With the resulting 2.27.0-SNAPSHOT jars and Disruptor 4.0.0, your program writes all 800,000 lines. Could you check it in your server when you have time?

  7. 9 remaining items

  8. ramanathan1504 commented on Oct 6, 2026

    @ramanathan1504
    Contributor

    @plusterkopp

    Thanks for testing it in your server. Good to hear no events are discarded.

    The idle RollingFileManager threads are not from this fix. They come from #4165 on 2.x, which made each rolling appender keep one thread after its first rollover. Do you have about 30 rolling file appenders? If so, that explains the count. I will open a separate issue for it.

    No need to try 2.26.2. It does not have this fix yet.

    For source jars, add source:jar-no-fork:

    ./mvnw source:jar-no-fork install -pl :log4j-api-java9,:log4j-core-java9,:log4j-core -am -DskipTests

  9. ramanathan1504 commented on Oct 6, 2026

    @ramanathan1504
    Contributor

    @plusterkopp, thanks for spotting the idle RollingFileManager threads in #4356. They come from #4165, and this PR fixes them.

    If you are interested, could you try this PR in your server? You can build it the same way as before, on this PR's branch:

    ./mvnw install -pl :log4j-api-java9,:log4j-core-java9,:log4j-core -am -DskipTests
    With it, the threads should end about a second after each rollover. No pressure if you do not have time.

  10. plusterkopp commented on Oct 7, 2026

    @plusterkopp
    Author

    With it, the threads should end about a second after each rollover.

    They do. All lines logged, no extra threads.

  11. laikamanor commented on Oct 9, 2026

    @laikamanor

    Hello,
    I would like to ask if the v2.26.2 will release today?

  12. ramanathan1504 commented on Oct 9, 2026

    @ramanathan1504
    Contributor

    @laikamanor

    No, two issues are still unresolved. After closing them, we will need to port the changes. Taking that into account, the timeline could slip to the first week of November in a worst-case scenario.

    Thanks!

  13. laikamanor commented on Oct 12, 2026

    @laikamanor

    Thanks for the update @ramanathan1504,
    One quick question: will the upcoming 2.26.2 release also address sonatype-2026-006746, or is that advisory currently considered out of scope for the planned fixes?

  14. ramanathan1504 commented on Oct 12, 2026

    @ramanathan1504
    Contributor

    @laikamanor, we does not treat that report as a vulnerability, see the FAQ and #4255. Still, the hardening changes from 2.x are planned for 2.26.2 and are being ported in #4386. They include #4271, which removes the MarshalledObject path the advisory describes.

    The advisory itself is maintained by Sonatype, not by the Log4j project. Your scanner may keep showing it until Sonatype lists 2.26.2 as a fixed version. Until then, most tools let you mark it as not applicable if your application does not deserialize log events from untrusted sources.

  15. ppkarwasz commented on Oct 13, 2026

    @ppkarwasz
    Member

    @laikamanor,

    Currently we are at Community over Code, but we can cut a 2.25.6 release after we come back. As @ramanathan1504 explained, there is really nothing to fix: FilteredObjectInputStream is not used anywhere and it offers the same security as ObjectInputStream from the JDK (i.e. barely any 🤣 ).

    Nevertheless, we understand some of our users are unable to upgrade Log4j without a “fix”.

  16. cforce07 commented on Nov 2, 2026

    @cforce07

    @ppkarwasz @ramanathan1504
    how is the progress over this release of 2.26.2 ? how far are we from the release completion ?

    if we are still very far from that, is that possible to cut the changes into separate release ?

  17. ramanathan1504 commented on Nov 4, 2026

    @ramanathan1504
    Contributor

    28. @ppkarwasz @ramanathan1504
    how is the progress over this release of 2.26.2 ? how far are we from the release completion ?
    if we are still very far from that, is that possible to cut the changes into separate release ?

    We planned the releases before Christmas Holidays. Thanks for your patience🙏

  18. added
    priority: P1
    and removed
    java
    on Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

asyncbugpriority: P1

Type

No type

Projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions