This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/master by this push:
     new 51bee60175 Do not store the default current project in threads that 
only read it (#13794)
51bee60175 is described below

commit 51bee60175f3648b5932db965c199aafd1cc4ccc
Author: Christian Munier <[email protected]>
AuthorDate: Tue Nov 3 18:21:03 2026 +0100

    Do not store the default current project in threads that only read it 
(#13794)
    
    MavenSession kept the current project in a ThreadLocal created with
    ThreadLocal.withInitial(...), and clone() gave every clone a new one.
    With withInitial, a plain get() on a thread without a value stores the
    initial value in that thread's ThreadLocalMap. Every thread that only
    read getCurrentProject() therefore kept a strong reference to the
    default project, and clone() itself reads the current project of the
    original session. After the session is discarded, these stale entries
    keep the project, and through it the whole build, reachable as long as
    the thread lives, e.g. on ForkJoinPool.commonPool workers in mvnd.
    
    The default project is now kept in a field, and the ThreadLocal holds
    only explicitly set projects (null is stored as Optional.empty()).
    Reading the current project on a thread without a value returns the
    default without storing it. The behavior is unchanged.
    
    Co-Authored-By: Claude Code (Anthropic Claude Opus 5.5, claude-opus-5-5)
---
 .../org/apache/maven/execution/MavenSession.java   | 24 ++++++++++++-----
 .../apache/maven/execution/MavenSessionTest.java   | 31 ++++++++++++++++++++++
 2 files changed, 48 insertions(+), 7 deletions(-)

diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java 
b/impl/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
index b50b345bfd..9e7770377d 100644
--- a/impl/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
+++ b/impl/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
@@ -25,6 +25,7 @@
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Properties;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
@@ -62,7 +63,13 @@ public class MavenSession implements Cloneable {
 
     private final Properties executionProperties;
 
-    private ThreadLocal<MavenProject> currentProject = new ThreadLocal<>();
+    /**
+     * The current project set on a thread, {@link Optional#empty()} if it was 
set to {@code null}. Threads without a
+     * value use {@link #defaultProject}, so that reading the current project 
never stores a project in the thread.
+     */
+    private ThreadLocal<Optional<MavenProject>> currentProject = new 
ThreadLocal<>();
+
+    private MavenProject defaultProject;
 
     /**
      * These projects have already been topologically sorted in the {@link 
org.apache.maven.Maven} component before
@@ -97,10 +104,12 @@ public void setProjects(List<MavenProject> projects) {
                     .filter(project -> project.isExecutionRoot())
                     .findFirst()
                     .orElse(projects.get(0));
-            this.currentProject = ThreadLocal.withInitial(() -> 
topLevelProject);
+            this.currentProject = new ThreadLocal<>();
+            this.defaultProject = topLevelProject;
             this.topLevelProject = topLevelProject;
         } else {
             this.currentProject = new ThreadLocal<>();
+            this.defaultProject = null;
             this.topLevelProject = null;
         }
         this.projects = projects;
@@ -172,11 +181,12 @@ public MavenExecutionRequest getRequest() {
     }
 
     public void setCurrentProject(MavenProject currentProject) {
-        this.currentProject.set(currentProject);
+        this.currentProject.set(Optional.ofNullable(currentProject));
     }
 
     public MavenProject getCurrentProject() {
-        return currentProject.get();
+        Optional<MavenProject> project = currentProject.get();
+        return project != null ? project.orElse(null) : defaultProject;
     }
 
     public ProjectBuildingRequest getProjectBuildingRequest() {
@@ -237,9 +247,9 @@ public MavenSession clone() {
         try {
             MavenSession clone = (MavenSession) super.clone();
             // the default must become the current project of the thread that 
clones this
-            MavenProject current = getCurrentProject();
-            // we replace the thread local of the clone to prevent write 
through and enforce the new default value
-            clone.currentProject = ThreadLocal.withInitial(() -> current);
+            clone.defaultProject = getCurrentProject();
+            // we replace the thread local of the clone to prevent write 
through
+            clone.currentProject = new ThreadLocal<>();
             return clone;
         } catch (CloneNotSupportedException e) {
             throw new RuntimeException("Bug", e);
diff --git 
a/impl/maven-core/src/test/java/org/apache/maven/execution/MavenSessionTest.java
 
b/impl/maven-core/src/test/java/org/apache/maven/execution/MavenSessionTest.java
index 8732d8e193..bf6b199daf 100644
--- 
a/impl/maven-core/src/test/java/org/apache/maven/execution/MavenSessionTest.java
+++ 
b/impl/maven-core/src/test/java/org/apache/maven/execution/MavenSessionTest.java
@@ -18,9 +18,11 @@
  */
 package org.apache.maven.execution;
 
+import java.lang.ref.WeakReference;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
 
@@ -156,6 +158,35 @@ void testCloneKeepsRuntimeCurrentProject() throws 
Exception {
         assertSame(root, session.getCurrentProject());
     }
 
+    @Test
+    void testReadingCurrentProjectOnOtherThreadDoesNotRetainProject() throws 
Exception {
+        ExecutorService executor = Executors.newSingleThreadExecutor();
+        try {
+            WeakReference<MavenProject> root = 
readCurrentProjectOnThread(executor);
+            for (int i = 0; i < 10 && root.get() != null; i++) {
+                System.gc();
+                Thread.sleep(10);
+            }
+            assertNull(root.get(), "the thread must not retain the project 
after the session is discarded");
+        } finally {
+            executor.shutdownNow();
+        }
+    }
+
+    private WeakReference<MavenProject> 
readCurrentProjectOnThread(ExecutorService executor) throws Exception {
+        MavenSession session = createSessionWithoutContainer();
+        MavenProject root = new MavenProject();
+        root.setExecutionRoot(true);
+        session.setProjects(List.of(root));
+        executor.submit(() -> {
+                    assertSame(root, session.getCurrentProject());
+                    MavenSession clone = session.clone();
+                    assertSame(root, clone.getCurrentProject());
+                })
+                .get(10, TimeUnit.SECONDS);
+        return new WeakReference<>(root);
+    }
+
     /**
      * Creates a MavenSession without a PlexusContainer (Maven 4 style).
      */

Reply via email to