Copilot commented on code in PR #481:
URL: 
https://github.com/apache/maven-build-cache-extension/pull/481#discussion_r3167346116


##########
src/main/java/org/apache/maven/buildcache/HostnameResolver.java:
##########
@@ -0,0 +1,88 @@
+/*
+ * 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.buildcache;
+
+import java.net.InetAddress;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * Resolves and caches the canonical host name of the local machine.
+ * <p>
+ * The lookup is performed asynchronously in a separate thread because
+ * {@code InetAddress.getLocalHost().getCanonicalHostName()} may block for a
+ * considerable amount of time in environments with slow or misconfigured name
+ * resolution (for example DNS or mDNS timeouts).
+ * <p>
+ * To avoid delaying application processing, the caller waits only up to
+ * {@value #TIMEOUT_MS} ms for the result. If the lookup does not complete in
+ * time or fails, the fallback value {@value #FALLBACK} is used instead.
+ * <p>
+ * The resolved value is cached after the first call to
+ * {@link #resolve()}.
+ */
+public final class HostnameResolver {
+
+    private static final String FALLBACK = "unknown";
+    private static final long TIMEOUT_MS = 1000;
+    private static String hostname;
+
+    private HostnameResolver() {
+        // utility class
+    }
+
+    public static String resolve() {
+        if (hostname == null) {
+            ExecutorService executor = Executors.newSingleThreadExecutor();
+            try {
+
+                Future<String> future = executor.submit(() -> {
+                    try {
+                        return 
InetAddress.getLocalHost().getCanonicalHostName();
+                    } catch (Exception e) {
+                        return null;
+                    }
+                });
+
+                String resolved;
+                try {
+                    resolved = future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+                } catch (TimeoutException e) {
+                    future.cancel(true);
+                    resolved = FALLBACK;
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    resolved = FALLBACK;
+                } catch (ExecutionException e) {
+                    resolved = FALLBACK;
+                }
+
+                hostname = (resolved == null || resolved.trim().isEmpty()) ? 
FALLBACK : resolved.trim();
+            } finally {
+                executor.shutdownNow();
+            }
+        }
+
+        return hostname;

Review Comment:
   `resolve()` uses a racy lazy-init (`if (hostname == null)`) with a 
non-volatile static field. In parallel Maven builds (`-T`), multiple threads 
can enter this block and spawn multiple hostname lookups (potentially each 
blocking for ~30s), and the cached value also has no safe publication 
guarantees. Consider making the cache initialization thread-safe (e.g., 
`volatile` + synchronized/lock, or an `AtomicReference`/`CompletableFuture` 
memoization) so only one lookup is ever started and the result is safely 
published.
   ```suggestion
       private static volatile String hostname;
   
       private HostnameResolver() {
           // utility class
       }
   
       public static String resolve() {
           String cached = hostname;
           if (cached != null) {
               return cached;
           }
   
           synchronized (HostnameResolver.class) {
               cached = hostname;
               if (cached == null) {
                   ExecutorService executor = 
Executors.newSingleThreadExecutor();
                   try {
   
                       Future<String> future = executor.submit(() -> {
                           try {
                               return 
InetAddress.getLocalHost().getCanonicalHostName();
                           } catch (Exception e) {
                               return null;
                           }
                       });
   
                       String resolved;
                       try {
                           resolved = future.get(TIMEOUT_MS, 
TimeUnit.MILLISECONDS);
                       } catch (TimeoutException e) {
                           future.cancel(true);
                           resolved = FALLBACK;
                       } catch (InterruptedException e) {
                           Thread.currentThread().interrupt();
                           resolved = FALLBACK;
                       } catch (ExecutionException e) {
                           resolved = FALLBACK;
                       }
   
                       cached = (resolved == null || resolved.trim().isEmpty()) 
? FALLBACK : resolved.trim();
                       hostname = cached;
                   } finally {
                       executor.shutdownNow();
                   }
               }
           }
   
           return cached;
   ```



##########
src/main/java/org/apache/maven/buildcache/HostnameResolver.java:
##########
@@ -0,0 +1,88 @@
+/*
+ * 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.buildcache;
+
+import java.net.InetAddress;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * Resolves and caches the canonical host name of the local machine.
+ * <p>
+ * The lookup is performed asynchronously in a separate thread because
+ * {@code InetAddress.getLocalHost().getCanonicalHostName()} may block for a
+ * considerable amount of time in environments with slow or misconfigured name
+ * resolution (for example DNS or mDNS timeouts).
+ * <p>
+ * To avoid delaying application processing, the caller waits only up to
+ * {@value #TIMEOUT_MS} ms for the result. If the lookup does not complete in
+ * time or fails, the fallback value {@value #FALLBACK} is used instead.
+ * <p>
+ * The resolved value is cached after the first call to
+ * {@link #resolve()}.
+ */
+public final class HostnameResolver {
+
+    private static final String FALLBACK = "unknown";
+    private static final long TIMEOUT_MS = 1000;
+    private static String hostname;
+
+    private HostnameResolver() {
+        // utility class
+    }
+
+    public static String resolve() {
+        if (hostname == null) {
+            ExecutorService executor = Executors.newSingleThreadExecutor();

Review Comment:
   `Executors.newSingleThreadExecutor()` uses a non-daemon thread by default. 
If `InetAddress.getLocalHost()` blocks beyond the timeout, the task thread can 
keep running in the background and may delay JVM shutdown (the thread is 
non-daemon) even though `resolve()` already returned. Use a daemon 
`ThreadFactory` (and ideally a shared/single executor) so a stuck resolver 
thread can’t keep the Maven process alive.



##########
src/main/java/org/apache/maven/buildcache/HostnameResolver.java:
##########
@@ -0,0 +1,88 @@
+/*
+ * 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.buildcache;
+
+import java.net.InetAddress;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * Resolves and caches the canonical host name of the local machine.
+ * <p>
+ * The lookup is performed asynchronously in a separate thread because
+ * {@code InetAddress.getLocalHost().getCanonicalHostName()} may block for a
+ * considerable amount of time in environments with slow or misconfigured name
+ * resolution (for example DNS or mDNS timeouts).
+ * <p>
+ * To avoid delaying application processing, the caller waits only up to
+ * {@value #TIMEOUT_MS} ms for the result. If the lookup does not complete in
+ * time or fails, the fallback value {@value #FALLBACK} is used instead.
+ * <p>
+ * The resolved value is cached after the first call to
+ * {@link #resolve()}.
+ */
+public final class HostnameResolver {
+
+    private static final String FALLBACK = "unknown";
+    private static final long TIMEOUT_MS = 1000;
+    private static String hostname;
+
+    private HostnameResolver() {
+        // utility class
+    }
+
+    public static String resolve() {
+        if (hostname == null) {
+            ExecutorService executor = Executors.newSingleThreadExecutor();
+            try {
+
+                Future<String> future = executor.submit(() -> {
+                    try {
+                        return 
InetAddress.getLocalHost().getCanonicalHostName();
+                    } catch (Exception e) {
+                        return null;
+                    }
+                });
+
+                String resolved;
+                try {
+                    resolved = future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
+                } catch (TimeoutException e) {
+                    future.cancel(true);
+                    resolved = FALLBACK;
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    resolved = FALLBACK;
+                } catch (ExecutionException e) {
+                    resolved = FALLBACK;
+                }
+
+                hostname = (resolved == null || resolved.trim().isEmpty()) ? 
FALLBACK : resolved.trim();
+            } finally {
+                executor.shutdownNow();
+            }
+        }
+
+        return hostname;
+    }

Review Comment:
   This introduces new timeout/caching behavior but there are no tests covering 
it. Since the project already has unit tests, please add coverage to ensure (1) 
`resolve()` returns the fallback quickly when the lookup is slow, and (2) the 
resolved/fallback value is cached (and that concurrent callers don’t trigger 
multiple lookups). To make this testable, consider injecting the lookup 
function/executor or factoring the DNS call behind a package-private strategy.
   ```suggestion
       interface HostnameLookup {
           String lookup() throws Exception;
       }
   
       interface ExecutorServiceFactory {
           ExecutorService create();
       }
   
       private static final String FALLBACK = "unknown";
       private static final long TIMEOUT_MS = 1000;
       private static final Object LOCK = new Object();
       private static volatile String hostname;
       private static volatile HostnameLookup hostnameLookup =
               () -> InetAddress.getLocalHost().getCanonicalHostName();
       private static volatile ExecutorServiceFactory executorServiceFactory = 
Executors::newSingleThreadExecutor;
   
       private HostnameResolver() {
           // utility class
       }
   
       public static String resolve() {
           String cached = hostname;
           if (cached != null) {
               return cached;
           }
   
           synchronized (LOCK) {
               cached = hostname;
               if (cached == null) {
                   cached = resolveHostname();
                   hostname = cached;
               }
               return cached;
           }
       }
   
       private static String resolveHostname() {
           ExecutorService executor = executorServiceFactory.create();
           try {
               Future<String> future = executor.submit(() -> {
                   try {
                       return hostnameLookup.lookup();
                   } catch (Exception e) {
                       return null;
                   }
               });
   
               String resolved;
               try {
                   resolved = future.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
               } catch (TimeoutException e) {
                   future.cancel(true);
                   resolved = FALLBACK;
               } catch (InterruptedException e) {
                   Thread.currentThread().interrupt();
                   resolved = FALLBACK;
               } catch (ExecutionException e) {
                   resolved = FALLBACK;
               }
   
               return (resolved == null || resolved.trim().isEmpty()) ? 
FALLBACK : resolved.trim();
           } finally {
               executor.shutdownNow();
           }
       }
   
       static void setHostnameLookupForTesting(HostnameLookup lookup) {
           hostnameLookup = lookup;
       }
   
       static void setExecutorServiceFactoryForTesting(ExecutorServiceFactory 
factory) {
           executorServiceFactory = factory;
       }
   
       static void resetForTesting() {
           synchronized (LOCK) {
               hostname = null;
               hostnameLookup = () -> 
InetAddress.getLocalHost().getCanonicalHostName();
               executorServiceFactory = Executors::newSingleThreadExecutor;
           }
       }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to