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

pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi-xmlbeans.git


The following commit(s) were added to refs/heads/trunk by this push:
     new 710b7e40 XMLBEANS-616: break the static initialization ring between 
XmlBeans and SchemaTypeLoaderBase (#158)
710b7e40 is described below

commit 710b7e4097fdf9cea99a732e4cc028d6b1b9064c
Author: Christian Appl <[email protected]>
AuthorDate: Wed Nov 4 11:15:21 2026 +0100

    XMLBEANS-616: break the static initialization ring between XmlBeans and 
SchemaTypeLoaderBase (#158)
    
    XmlBeans.<clinit> needs SchemaTypeLoaderBase for NO_TYPE (through
    BuiltinSchemaTypeSystem), and SchemaTypeLoaderBase.<clinit> read
    XmlBeans for its USER_AGENT field. Two threads touching XMLBeans for
    the first time at once, one through XmlObject.Factory and one through
    a generated type, each held one of the two class initializations and
    waited for the other forever.
    
    The user agent is now built where it is used, when a schema is fetched
    over HTTP, so SchemaTypeLoaderBase no longer depends on XmlBeans while
    it initializes. The header value is unchanged.
    
    StaticInitializationRingTest reproduces the race in one JVM, loading
    XMLBeans in a class loader of its own for every attempt. Whatever a
    thread throws fails the test, so a class path problem cannot pass as
    no deadlock.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../xmlbeans/impl/schema/SchemaTypeLoaderBase.java |  13 ++-
 .../detailed/StaticInitializationRingTest.java     | 109 +++++++++++++++++++++
 2 files changed, 120 insertions(+), 2 deletions(-)

diff --git 
a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java 
b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
index a727404c..9650128b 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
@@ -37,7 +37,16 @@ import java.util.ArrayList;
 import java.util.List;
 
 public abstract class SchemaTypeLoaderBase implements SchemaTypeLoader {
-    private static final String USER_AGENT = "XMLBeans/" + 
XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")";
+    /**
+     * The User-Agent header sent when a schema is fetched over HTTP. It is 
built where it is used and not in a static
+     * field: XmlBeans' own static initialization needs this class 
(XmlBeans.NO_TYPE comes from BuiltinSchemaTypeSystem,
+     * a subclass), so reading XmlBeans while this class initializes closed a 
ring between the two class
+     * initializations. Two threads entering it from opposite ends at the same 
time - one through XmlObject.Factory,
+     * one through a generated type - waited for each other forever 
(XMLBEANS-616).
+     */
+    private static String userAgent() {
+        return "XMLBeans/" + XmlBeans.getVersion() + " (" + 
XmlBeans.getTitle() + ")";
+    }
 
     private static String doCompilePath(String pathExpr, XmlOptions options) {
         return XPathFactory.compilePath(pathExpr, options);
@@ -182,7 +191,7 @@ public abstract class SchemaTypeLoaderBase implements 
SchemaTypeLoader {
 
         do {
             conn = url.openConnection();
-            conn.addRequestProperty("User-Agent", USER_AGENT);
+            conn.addRequestProperty("User-Agent", userAgent());
             conn.addRequestProperty("Accept", "application/xml, text/xml, 
*/*");
             if (conn instanceof HttpURLConnection httpcon) {
                 int code = httpcon.getResponseCode();
diff --git a/src/test/java/misc/detailed/StaticInitializationRingTest.java 
b/src/test/java/misc/detailed/StaticInitializationRingTest.java
new file mode 100644
index 00000000..6013de75
--- /dev/null
+++ b/src/test/java/misc/detailed/StaticInitializationRingTest.java
@@ -0,0 +1,109 @@
+/*   Copyright 2004 The Apache Software Foundation
+ *
+ *   Licensed 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 misc.detailed;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * XMLBEANS-616: two threads that touch XMLBeans for the first time at once, 
one through {@code XmlObject.Factory} and
+ * one through a generated type, must not wait for each other forever.
+ *
+ * <p>{@code XmlBeans.<clinit>} needs {@code SchemaTypeLoaderBase} (for {@code 
NO_TYPE}, through its subclass
+ * {@code BuiltinSchemaTypeSystem}); a static field of {@code 
SchemaTypeLoaderBase} read {@code XmlBeans} in turn. The
+ * first thread then held the initialization of {@code XmlBeans}, the second 
that of {@code SchemaTypeLoaderBase}, and
+ * each waited for the other's. Every attempt loads XMLBeans from the test 
class path in a class loader of its own, so
+ * its classes start uninitialized; the generated type is XMLBeans' own {@code 
SchemaDocument}.</p>
+ *
+ * <p>Whatever a thread throws fails the test, so that a class path problem or 
a renamed class cannot pass as "no
+ * deadlock".</p>
+ */
+public class StaticInitializationRingTest {
+
+    // Without the fix 9 of 20 attempts hung, so 10 attempts all pass by 
chance only about once in 400.
+    private static final int ATTEMPTS = 10;
+
+    private static final long TIMEOUT_MILLIS = 5000;
+
+    @Test
+    void firstContactFromBothEndsDoesNotDeadlock() throws Exception {
+        URL[] classPath = testClassPath();
+        for (int attempt = 1; attempt <= ATTEMPTS; attempt++) {
+            URLClassLoader loader = new URLClassLoader(classPath, 
ClassLoader.getPlatformClassLoader());
+            CountDownLatch start = new CountDownLatch(1);
+            AtomicReference<Throwable> untypedFailure = new 
AtomicReference<>();
+            AtomicReference<Throwable> typedFailure = new AtomicReference<>();
+            Thread untyped = touch(loader, start, 
"org.apache.xmlbeans.XmlObject", untypedFailure);
+            Thread typed = touch(loader, start, 
"org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument", typedFailure);
+            start.countDown();
+            untyped.join(TIMEOUT_MILLIS);
+            typed.join(TIMEOUT_MILLIS);
+            boolean hung = untyped.isAlive() || typed.isAlive();
+            if (!hung) {
+                // a hung thread keeps its loader; only a finished attempt can 
let it go
+                loader.close();
+            }
+            assertFalse(hung, "attempt " + attempt + ": the first contact from 
both ends of the static "
+                + "initialization deadlocked");
+            failOn(untypedFailure, "XmlObject", attempt);
+            failOn(typedFailure, "SchemaDocument", attempt);
+        }
+    }
+
+    private static void failOn(AtomicReference<Throwable> failure, String 
entry, int attempt) {
+        if (failure.get() != null) {
+            fail("attempt " + attempt + ": the first contact through " + entry 
+ " failed, so the attempt says "
+                + "nothing about the deadlock", failure.get());
+        }
+    }
+
+    private static URL[] testClassPath() throws MalformedURLException {
+        List<URL> urls = new ArrayList<>();
+        for (String entry : 
System.getProperty("java.class.path").split(File.pathSeparator)) {
+            urls.add(new File(entry).toURI().toURL());
+        }
+        return urls.toArray(new URL[0]);
+    }
+
+    private static Thread touch(ClassLoader loader, CountDownLatch start, 
String type,
+                                AtomicReference<Throwable> failure) {
+        Thread thread = new Thread(() -> {
+            try {
+                start.await();
+                Object factory = Class.forName(type, true, 
loader).getField("Factory").get(null);
+                factory.getClass().getMethod("newInstance").invoke(factory);
+            } catch (Throwable t) {
+                // also Errors: a failed class initialization throws 
ExceptionInInitializerError,
+                // a missing class NoClassDefFoundError
+                failure.set(t);
+            }
+        });
+        thread.setDaemon(true);
+        thread.start();
+        return thread;
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to