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

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


The following commit(s) were added to refs/heads/maven-3.10.x by this push:
     new 7dda713042 Do not store the default current project in threads that 
only read it (#13794) (#13803)
7dda713042 is described below

commit 7dda713042806ae91b342f9116cf13b1c491b571
Author: Guillaume Nodet <[email protected]>
AuthorDate: Tue Nov 3 21:34:43 2026 +0100

    Do not store the default current project in threads that only read it 
(#13794) (#13803)
    
    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)
    
    Co-authored-by: Christian Munier <[email protected]>
---
 .../org/apache/maven/execution/MavenSession.java   | 24 +++++--
 .../apache/maven/execution/MavenSessionTest.java   | 75 ++++++++++++++++++++++
 2 files changed, 92 insertions(+), 7 deletions(-)

diff --git 
a/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java 
b/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
index bd128baa88..132c8095d1 100644
--- a/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
+++ b/maven-core/src/main/java/org/apache/maven/execution/MavenSession.java
@@ -27,6 +27,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.Optional;
 import java.util.Properties;
 import java.util.concurrent.ConcurrentHashMap;
 
@@ -56,7 +57,13 @@ public class MavenSession implements Cloneable {
 
     private 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
@@ -85,13 +92,15 @@ public class MavenSession implements Cloneable {
     public void setProjects(List<MavenProject> projects) {
         if (!projects.isEmpty()) {
             MavenProject first = projects.get(0);
-            this.currentProject = ThreadLocal.withInitial(() -> first);
+            this.currentProject = new ThreadLocal<>();
+            this.defaultProject = first;
             this.topLevelProject = projects.stream()
                     .filter(project -> project.isExecutionRoot())
                     .findFirst()
                     .orElse(first);
         } else {
             this.currentProject = new ThreadLocal<>();
+            this.defaultProject = null;
             this.topLevelProject = null;
         }
         this.projects = projects;
@@ -143,11 +152,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() {
@@ -238,9 +248,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/maven-core/src/test/java/org/apache/maven/execution/MavenSessionTest.java 
b/maven-core/src/test/java/org/apache/maven/execution/MavenSessionTest.java
new file mode 100644
index 0000000000..7cb62c94e1
--- /dev/null
+++ b/maven-core/src/test/java/org/apache/maven/execution/MavenSessionTest.java
@@ -0,0 +1,75 @@
+/*
+ * 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.maven.execution;
+
+import java.lang.ref.WeakReference;
+import java.util.Collections;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.maven.project.MavenProject;
+import org.eclipse.aether.RepositorySystemSession;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.mockito.Mockito.mock;
+
+/**
+ * Tests for {@link MavenSession}.
+ */
+class MavenSessionTest {
+
+    @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 = createSession();
+        MavenProject root = new MavenProject();
+        root.setExecutionRoot(true);
+        session.setProjects(Collections.singletonList(root));
+        executor.submit(() -> {
+                    assertSame(root, session.getCurrentProject());
+                    MavenSession clone = session.clone();
+                    assertSame(root, clone.getCurrentProject());
+                })
+                .get(10, TimeUnit.SECONDS);
+        return new WeakReference<>(root);
+    }
+
+    private MavenSession createSession() {
+        RepositorySystemSession repoSession = 
mock(RepositorySystemSession.class);
+        MavenExecutionRequest request = new DefaultMavenExecutionRequest();
+        MavenExecutionResult result = new DefaultMavenExecutionResult();
+        return new MavenSession(null, repoSession, request, result);
+    }
+}

Reply via email to