This is an automated email from the ASF dual-hosted git repository.
coheigea pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/cxf.git
The following commit(s) were added to refs/heads/main by this push:
new c1b566034b0 Make the StAX factory caches in StaxIn/StaxOutInterceptor
thread-safe (#3788)
c1b566034b0 is described below
commit c1b566034b0770cecdfe1dda7bbdfd5e9b1e684b
Author: Colm O hEigeartaigh <[email protected]>
AuthorDate: Thu Nov 26 13:45:07 2026 +0000
Make the StAX factory caches in StaxIn/StaxOutInterceptor thread-safe
(#3788)
* Make the StAX factory caches in StaxIn/StaxOutInterceptor thread-safe
* Addressing review comments
* Adding test
---
.../apache/cxf/interceptor/StaxInInterceptor.java | 21 ++-
.../apache/cxf/interceptor/StaxOutInterceptor.java | 21 ++-
.../cxf/interceptor/StaxFactoryCacheTest.java | 147 +++++++++++++++++++++
3 files changed, 167 insertions(+), 22 deletions(-)
diff --git
a/core/src/main/java/org/apache/cxf/interceptor/StaxInInterceptor.java
b/core/src/main/java/org/apache/cxf/interceptor/StaxInInterceptor.java
index d40daa30483..693461371f0 100644
--- a/core/src/main/java/org/apache/cxf/interceptor/StaxInInterceptor.java
+++ b/core/src/main/java/org/apache/cxf/interceptor/StaxInInterceptor.java
@@ -23,10 +23,9 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
-import java.lang.reflect.InvocationTargetException;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import javax.xml.stream.XMLInputFactory;
@@ -52,7 +51,7 @@ public class StaxInInterceptor extends
AbstractPhaseInterceptor<Message> {
private static final Logger LOG =
LogUtils.getL7dLogger(StaxInInterceptor.class);
- private static Map<Object, XMLInputFactory> factories = new HashMap<>();
+ private static final Map<Object, XMLInputFactory> FACTORIES = new
ConcurrentHashMap<>();
public StaxInInterceptor() {
super(Phase.POST_STREAM);
@@ -164,7 +163,7 @@ public class StaxInInterceptor extends
AbstractPhaseInterceptor<Message> {
if (o instanceof XMLInputFactory) {
return (XMLInputFactory)o;
} else if (o != null) {
- XMLInputFactory xif = factories.get(o);
+ XMLInputFactory xif = FACTORIES.get(o);
if (xif == null) {
Class<?> cls;
if (o instanceof Class) {
@@ -181,13 +180,13 @@ public class StaxInInterceptor extends
AbstractPhaseInterceptor<Message> {
LOG, o));
}
- try {
- xif =
(XMLInputFactory)(cls.getDeclaredConstructor().newInstance());
- factories.put(o, xif);
- } catch (InstantiationException | IllegalAccessException |
IllegalArgumentException
- | InvocationTargetException | NoSuchMethodException |
SecurityException e) {
- throw new Fault(e);
- }
+ xif = FACTORIES.computeIfAbsent(o, k -> {
+ try {
+ return
(XMLInputFactory)cls.getDeclaredConstructor().newInstance();
+ } catch (ReflectiveOperationException |
IllegalArgumentException | SecurityException e) {
+ throw new Fault(e);
+ }
+ });
}
return xif;
}
diff --git
a/core/src/main/java/org/apache/cxf/interceptor/StaxOutInterceptor.java
b/core/src/main/java/org/apache/cxf/interceptor/StaxOutInterceptor.java
index 08b6ca67a6f..6a8c06fcc05 100644
--- a/core/src/main/java/org/apache/cxf/interceptor/StaxOutInterceptor.java
+++ b/core/src/main/java/org/apache/cxf/interceptor/StaxOutInterceptor.java
@@ -21,11 +21,10 @@ package org.apache.cxf.interceptor;
import java.io.OutputStream;
import java.io.Writer;
-import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
-import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
@@ -54,7 +53,7 @@ public class StaxOutInterceptor extends
AbstractPhaseInterceptor<Message> {
= new StaxOutEndingInterceptor(OUTPUT_STREAM_HOLDER, WRITER_HOLDER);
private static final ResourceBundle BUNDLE =
BundleUtils.getBundle(StaxOutInterceptor.class);
- private static Map<Object, XMLOutputFactory> factories = new HashMap<>();
+ private static final Map<Object, XMLOutputFactory> FACTORIES = new
ConcurrentHashMap<>();
public StaxOutInterceptor() {
@@ -167,7 +166,7 @@ public class StaxOutInterceptor extends
AbstractPhaseInterceptor<Message> {
m.put(FORCE_START_DOCUMENT, Boolean.TRUE);
return (XMLOutputFactory)o;
} else if (o != null) {
- XMLOutputFactory xif = factories.get(o);
+ XMLOutputFactory xif = FACTORIES.get(o);
if (xif == null) {
Class<?> cls;
if (o instanceof Class) {
@@ -183,13 +182,13 @@ public class StaxOutInterceptor extends
AbstractPhaseInterceptor<Message> {
BUNDLE, o));
}
- try {
- xif =
(XMLOutputFactory)(cls.getDeclaredConstructor().newInstance());
- factories.put(o, xif);
- } catch (InstantiationException | IllegalAccessException |
IllegalArgumentException
- | InvocationTargetException | NoSuchMethodException |
SecurityException e) {
- throw new Fault(e);
- }
+ xif = FACTORIES.computeIfAbsent(o, k -> {
+ try {
+ return
(XMLOutputFactory)cls.getDeclaredConstructor().newInstance();
+ } catch (ReflectiveOperationException |
IllegalArgumentException | SecurityException e) {
+ throw new Fault(e);
+ }
+ });
}
m.put(AbstractOutDatabindingInterceptor.DISABLE_OUTPUTSTREAM_OPTIMIZATION,
Boolean.TRUE);
diff --git
a/core/src/test/java/org/apache/cxf/interceptor/StaxFactoryCacheTest.java
b/core/src/test/java/org/apache/cxf/interceptor/StaxFactoryCacheTest.java
new file mode 100644
index 00000000000..a1feeba7f9d
--- /dev/null
+++ b/core/src/test/java/org/apache/cxf/interceptor/StaxFactoryCacheTest.java
@@ -0,0 +1,147 @@
+/**
+ * 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.cxf.interceptor;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLOutputFactory;
+
+import com.ctc.wstx.stax.WstxInputFactory;
+import com.ctc.wstx.stax.WstxOutputFactory;
+
+import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageImpl;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class StaxFactoryCacheTest {
+
+ public static class CountingInputFactory extends WstxInputFactory {
+ static final AtomicInteger CREATED = new AtomicInteger();
+
+ public CountingInputFactory() {
+ CREATED.incrementAndGet();
+ }
+ }
+
+ public static class CountingOutputFactory extends WstxOutputFactory {
+ static final AtomicInteger CREATED = new AtomicInteger();
+
+ public CountingOutputFactory() {
+ CREATED.incrementAndGet();
+ }
+ }
+
+ private static Message message(String property, Object value) {
+ Message m = new MessageImpl();
+ m.put(property, value);
+ return m;
+ }
+
+ @Test
+ public void testInputFactoryFromClassNameIsCached() throws Exception {
+ String name = WstxInputFactory.class.getName();
+ XMLInputFactory first =
+
StaxInInterceptor.getXMLInputFactory(message(XMLInputFactory.class.getName(),
name));
+ XMLInputFactory second =
+
StaxInInterceptor.getXMLInputFactory(message(XMLInputFactory.class.getName(),
name));
+ assertTrue(first instanceof WstxInputFactory);
+ assertSame(first, second);
+ }
+
+ @Test
+ public void testOutputFactoryFromClassIsCached() throws Exception {
+ Message m1 = message(XMLOutputFactory.class.getName(),
WstxOutputFactory.class);
+ XMLOutputFactory first = StaxOutInterceptor.getXMLOutputFactory(m1);
+ XMLOutputFactory second =
+
StaxOutInterceptor.getXMLOutputFactory(message(XMLOutputFactory.class.getName(),
+
WstxOutputFactory.class));
+ assertTrue(first instanceof WstxOutputFactory);
+ assertSame(first, second);
+ assertEquals(Boolean.TRUE,
m1.get(StaxOutInterceptor.FORCE_START_DOCUMENT));
+ }
+
+ @Test
+ public void testNonInstantiableFactoryFailsEveryTime() throws Exception {
+ // XMLInputFactory cannot be instantiated, so construction fails and
nothing must be cached
+ for (int i = 0; i < 2; i++) {
+ try {
+
StaxInInterceptor.getXMLInputFactory(message(XMLInputFactory.class.getName(),
+
XMLInputFactory.class));
+ fail("Expected a Fault");
+ } catch (Fault expected) {
+ assertTrue(expected.getCause() instanceof
ReflectiveOperationException);
+ }
+ }
+ }
+
+ @Test
+ public void testConcurrentFirstAccessCreatesOneFactory() throws Exception {
+ assertEquals(1, concurrentlyCreate(() ->
StaxInInterceptor.getXMLInputFactory(
+ message(XMLInputFactory.class.getName(),
CountingInputFactory.class))));
+ assertEquals(1, CountingInputFactory.CREATED.get());
+
+ assertEquals(1, concurrentlyCreate(() ->
StaxOutInterceptor.getXMLOutputFactory(
+ message(XMLOutputFactory.class.getName(),
CountingOutputFactory.class))));
+ assertEquals(1, CountingOutputFactory.CREATED.get());
+ }
+
+ /**
+ * Calls the given task from several threads at once and returns the
number of distinct
+ * instances returned.
+ */
+ private static int concurrentlyCreate(Callable<Object> task) throws
Exception {
+ int threads = 16;
+ ExecutorService executor = Executors.newFixedThreadPool(threads);
+ try {
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<Object>> results = new ArrayList<>();
+ for (int i = 0; i < threads; i++) {
+ results.add(executor.submit(() -> {
+ start.await();
+ return task.call();
+ }));
+ }
+ start.countDown();
+ List<Object> distinct = new ArrayList<>();
+ for (Future<Object> f : results) {
+ Object o = f.get();
+ if (distinct.stream().noneMatch(d -> d == o)) {
+ distinct.add(o);
+ }
+ }
+ return distinct.size();
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+}