From eea1cf0b2df5b45fdff3be0d446e309ab840f650 Mon Sep 17 00:00:00 2001 From: Pierre De Rop Date: Thu, 26 Nov 2026 21:22:50 -0600 Subject: [PATCH] FELIX-6893: Fix DispatchExecutor reentrancy race with a task counter Motivation: A thread executing a DispatchExecutor queue must run its reentrant tasks inline (e.g. component.add(dependency) from init()). The end of run() released the queue before clearing the executing thread: m_scheduled.set(false); m_executingThread = null; Scenario: thread A, from the threadpool, finishes the queue and releases it. Thread B (a REMOVED event or stop(), which bypass the threadpool) then takes the queue over and sets itself as the executing thread. A then overwrites it with null. When a task running in B calls execute() again, B is no longer recognized as the queue owner: the task is queued instead of being run inline, and the component goes on (e.g. start()) before it has run. Modification: Rewrite DispatchExecutor around a counter of pending tasks: the thread which increments it from 0 owns the queue and runs tasks until it drops back to 0. The owner only clears the executing thread if no other thread has taken the queue over in the meantime. Task execution never throws, so the counter stays consistent. Unused methods are removed. Result: Reentrant tasks are always executed inline by the thread which owns the queue, and DispatchExecutor is much simpler. --- .../felix/dm/impl/DispatchExecutor.java | 206 ++++++------------ ...IX6893_DispatchExecutorReentrancyTest.java | 102 +++++++++ 2 files changed, 173 insertions(+), 135 deletions(-) create mode 100644 dependencymanager/org.apache.felix.dependencymanager/test/org/apache/felix/dm/impl/FELIX6893_DispatchExecutorReentrancyTest.java diff --git a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/DispatchExecutor.java b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/DispatchExecutor.java index a780231370..ed29c9d487 100644 --- a/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/DispatchExecutor.java +++ b/dependencymanager/org.apache.felix.dependencymanager/src/org/apache/felix/dm/impl/DispatchExecutor.java @@ -21,167 +21,103 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.apache.felix.dm.Logger; import org.osgi.service.log.LogService; -/** - * A DispatchExecutor is a queue that can execute FIFO tasks in a shared threadpool configured for the dispatcher. - * Each task scheduled in a given DispatchExecutor will be executed serially in FIFO order; and multiple - * DispatchExecutor instances may each run concurrently with respect to each other. +/** + * A lock free queue of tasks executed serially, in FIFO order, either in a shared threadpool or + * from the caller thread. Many DispatchExecutor instances may run concurrently in the same threadpool. *

- * - * This class also supports synchronous scheduling, like the @link {@link SerialExecutor} class; and in this case, - * only one caller thread will execute the tasks scheduled in the DispatchQueue (and the internal - * threadpool won't be used). - * - *

- * - * This class is lock free by design and ensures "safe object publication" between scheduling threads and - * actual executing thread: if one thread T1 schedules a task, but another thread T2 actually - * executes it, then all the objects from the T1 thread will be "safely published" to the executing T2 thread. - * Safe publication is ensured because we are using a ConcurrentLinkedQueue, and volatile attributes. - * (see [1], chapter 3.5.3 (Safe publication idioms). - * - * [1] Java Concurrency In Practice, Addison Wesley - * + * A task scheduled by the thread which is currently executing the queue is run inline (immediately). + *

+ * {@code m_pending} counts the tasks submitted but not yet executed: the thread which increments it + * from 0 becomes the owner of the queue, and runs tasks until the counter drops back to 0. + * Safe publication between the submitting threads and the owner is ensured by the concurrent queue + * and the atomic counter. + * * @author Felix Project Team */ public class DispatchExecutor implements Executor, Runnable { - /** - * The threadpool used for the execution of the tasks that are scheduled in this queue. - */ - private final Executor m_threadPool; - - /** - * List of tasks scheduled in our queue. - */ - protected final ConcurrentLinkedQueue m_tasks = new ConcurrentLinkedQueue<>(); + private final ConcurrentLinkedQueue m_tasks = new ConcurrentLinkedQueue<>(); + private final AtomicInteger m_pending = new AtomicInteger(); + private final AtomicReference m_executingThread = new AtomicReference<>(); + private final Executor m_threadPool; + private final Logger m_logger; - /** - * Marker used to remember the id of the thread currently executing this dispatch queue. - */ - private volatile Thread m_executingThread; - - /** - * Flag telling if this dispatch queue is already scheduled for execution in the threadpool. - */ - private final AtomicBoolean m_scheduled = new AtomicBoolean(); - - /** - * Logger used to log exceptions thrown by scheduled tasks. - */ - private final Logger m_logger; - - /** - * Creates a new DispatchQueue, which can be executed within a fixed thread pool. Multiple queue - * can be executed concurrently, but all runnables scheduled in a given queue will be executed serially, - * in FIFO order. - * - * @param threadPool the executor (typically a threadpool) used to execute this DispatchExecutor. - * @param logger the Logger used when errors are taking place - */ public DispatchExecutor(Executor threadPool, Logger logger) { - m_logger = logger; - m_threadPool = threadPool; - } - + m_threadPool = threadPool; + m_logger = logger; + } + /** - * Enqueues a task for later execution. You must call {@link #execute()} in order - * to trigger the actual execution of all scheduled tasks (in FIFO order). + * Executes a task in the threadpool (or inline if called from the thread executing this queue). */ - public void schedule(Runnable task) { - m_tasks.add(task); + @Override + public void execute(Runnable task) { + execute(task, true); } - /** - * Submits a task in this queue, and schedule the execution of this DispatchQueue in the threadpool. - * The task is immediately executed (inline execution) if the queue is currently being executed by - * the current thread. - */ - public void execute(Runnable task) { - execute(task, true); - } - - /** - * Schedules a task in this queue. - * If the queue is currently being executed by the current thread, then the task is executed immediately. - * @tasks the task to schedule - * @threadpool true if the queue should be executed in the threadpool, false if the queue must be executed by - * only one caller thread. + /** + * Executes a task inline if called from the thread executing this queue. Otherwise, enqueues it and, + * if the queue is idle, executes the queue in the threadpool, or from the caller thread if + * {@code threadpool} is false. */ public void execute(Runnable task, boolean threadpool) { - Thread currThread = Thread.currentThread(); - if (m_executingThread == currThread) { + if (m_executingThread.get() == Thread.currentThread()) { runTask(task); - } else { - schedule(task); - execute(threadpool); + return; } - } - - /** - * Schedules the execution of this DispatchQueue in the threadpool. - */ - public void execute() { - execute(true); - } - - /** - * Schedules the execution of this DispatchQueue in the threadpool, or from a single caller thread. - * - * @param threadpool true means the DispatchQueue is executed in the threadpool, false means the queue is executed from the - * caller thread. - */ - public void execute(boolean threadpool) { - if (m_scheduled.compareAndSet(false, true)) { // schedules our run method in the tpool. - try { - if (threadpool) { + m_tasks.offer(task); + if (m_pending.getAndIncrement() == 0) { + if (threadpool) { + try { m_threadPool.execute(this); - } else { - run(); // run all queue tasks from the caller thread + } catch (RejectedExecutionException e) { + run(); // the threadpool is stopped (framework shutting down?): run from the caller thread } - } catch (RejectedExecutionException e) { - // The threadpool seems stopped (maybe the framework is being stopped). Anyway, just execute our tasks - // from the current thread. + } else { run(); } } } - /** - * Run all tasks scheduled in this queue, in FIFO order. This method may be executed either in the threadpool, or from - * the caller thread. - */ - @Override - public void run() { + /** + * Runs the queued tasks until the queue is empty. Only called by the owner of the queue. + */ + @Override + public void run() { + Thread self = Thread.currentThread(); + m_executingThread.set(self); + do { + runTask(m_tasks.poll()); + } while (m_pending.decrementAndGet() > 0); + queueReleased(); + // Another thread may already own the queue: only clear the executing thread if it is still us. + m_executingThread.compareAndSet(self, null); + } + + /** + * Called by the thread which has just executed this queue, right after it has released the queue + * (so another thread may already be executing it). Does nothing by default: only used by tests. + */ + void queueReleased() { + } + + /** + * Runs a task. Never throws: an exception escaping from run() would leave m_pending + * above 0, and the queue would never be executed again. + */ + private void runTask(Runnable task) { try { - // We do a memory barrier in order to ensure consistent per-thread - // memory visibility - m_executingThread = Thread.currentThread(); - Runnable task; - while ((task = m_tasks.poll()) != null) { - runTask(task); - } - } finally { - m_scheduled.set(false); - m_executingThread = null; - if (m_tasks.peek() != null) { - execute(); + task.run(); + } catch (Throwable t) { + try { + m_logger.log(LogService.LOG_ERROR, "Error processing tasks", t); + } catch (Throwable ignored) { } } - } - - /** - * Runs a given task - * @param task the task to execute - */ - private void runTask(Runnable task) { - try { - task.run(); - } catch (Throwable t) { - m_logger.log(LogService.LOG_ERROR, "Error processing tasks", t); - } - } + } } diff --git a/dependencymanager/org.apache.felix.dependencymanager/test/org/apache/felix/dm/impl/FELIX6893_DispatchExecutorReentrancyTest.java b/dependencymanager/org.apache.felix.dependencymanager/test/org/apache/felix/dm/impl/FELIX6893_DispatchExecutorReentrancyTest.java new file mode 100644 index 0000000000..a81f3123b7 --- /dev/null +++ b/dependencymanager/org.apache.felix.dependencymanager/test/org/apache/felix/dm/impl/FELIX6893_DispatchExecutorReentrancyTest.java @@ -0,0 +1,102 @@ +/* + * 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.felix.dm.impl; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.felix.dm.Logger; +import org.junit.Assert; +import org.junit.Test; + +/** + * FELIX-6893: a thread which is executing a DispatchExecutor queue must run its reentrant tasks inline, + * even if another thread has just finished executing the same queue. + * + * The pool thread is paused right after it has released the queue, while the test thread takes the + * queue over and executes it from the caller thread (threadpool bypassed, like for REMOVED events). + * Once the pool thread has completed its run, a reentrant task scheduled by the test thread must + * still be executed inline. + */ +public class FELIX6893_DispatchExecutorReentrancyTest { + private static final long TIMEOUT = 5; + + @Test + public void testReentrantTaskRunsInlineAfterQueueHandOver() throws Exception { + ExecutorService pool = Executors.newSingleThreadExecutor(); + try { + AtomicBoolean pauseOnRelease = new AtomicBoolean(true); + CountDownLatch poolThreadReleasedQueue = new CountDownLatch(1); + CountDownLatch callerThreadOwnsQueue = new CountDownLatch(1); + + DispatchExecutor exec = new DispatchExecutor(pool, new Logger(null)) { + @Override + void queueReleased() { + if (pauseOnRelease.compareAndSet(true, false)) { + poolThreadReleasedQueue.countDown(); + await(callerThreadOwnsQueue); + } + } + }; + + // The pool thread executes the queue, then pauses just after having released it. + exec.execute(() -> {}, true); + await(poolThreadReleasedQueue); + + AtomicBoolean reentrantTaskRunInline = new AtomicBoolean(); + CountDownLatch reentrantTaskDone = new CountDownLatch(1); + + // The test thread takes the queue over and executes it from the caller thread. + exec.execute(() -> { + callerThreadOwnsQueue.countDown(); + // Wait until the pool thread has completed its run (the single pool thread only runs this + // latch once DispatchExecutor.run() has returned). + CountDownLatch poolThreadDone = new CountDownLatch(1); + pool.execute(poolThreadDone::countDown); + await(poolThreadDone); + + boolean[] inline = new boolean[1]; + exec.execute(() -> { + inline[0] = true; + reentrantTaskDone.countDown(); + }, false); + reentrantTaskRunInline.set(inline[0]); + }, false); + + Assert.assertTrue("reentrant task not executed", reentrantTaskDone.await(TIMEOUT, TimeUnit.SECONDS)); + Assert.assertTrue("reentrant task was deferred instead of being executed inline", reentrantTaskRunInline.get()); + } finally { + pool.shutdownNow(); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(TIMEOUT, TimeUnit.SECONDS)) { + throw new IllegalStateException("timeout"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } +}