Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
2089d30
WW-5537 Add InternalDestroyable and ContextAwareDestroyable interfaces
lukaszlenart Mar 23, 2026
a64777a
WW-5537 ContainerHolder: ThreadLocal with AtomicLong generation counter
lukaszlenart Mar 23, 2026
7f51543
WW-5537 FinalizableReferenceQueue: volatile instance, join, classload…
lukaszlenart Mar 23, 2026
549291b
WW-5537 ScopeInterceptor.clearLocks: add synchronized block
lukaszlenart Mar 23, 2026
730d354
WW-5537 CompoundRootAccessor, DefaultFileManager: implement InternalD…
lukaszlenart Mar 23, 2026
2c4ac83
WW-5537 Add InternalDestroyable adapter classes for static cache cleanup
lukaszlenart Mar 23, 2026
7c02231
WW-5537 Register InternalDestroyable beans in struts-beans.xml
lukaszlenart Mar 23, 2026
16a7088
WW-5537 JSON plugin: add JSONCacheDestroyable for BeanInfo cache cleanup
lukaszlenart Mar 23, 2026
534e8cc
WW-5537 Dispatcher.cleanup: refactor into focused methods with Intern…
lukaszlenart Mar 23, 2026
50c715a
WW-5537 Rewrite DispatcherCleanupTest for InternalDestroyable discovery
lukaszlenart Mar 23, 2026
305f50f
WW-5537 Add log4j-web for proper Log4j2 lifecycle in Servlet container
lukaszlenart Mar 23, 2026
9097c07
WW-5537 Dispatcher.destroyObjectFactory: add early return on null, us…
lukaszlenart Mar 23, 2026
cfe097e
WW-5537 Fix @since annotations: 7.1.0 -> 7.2.0
lukaszlenart Mar 23, 2026
1296e4f
WW-5537 Add Container.destroy() to clear internal caches on undeploy
lukaszlenart Mar 23, 2026
d04becb
WW-5537 Fix Container.destroy(): don't clear factories, don't call fr…
lukaszlenart Mar 23, 2026
d9af5fd
WW-5537 Restore destroy() call in reloadContainer()
lukaszlenart Mar 23, 2026
86308cf
WW-5537 Fix Sonar issues: thread-safe FinalizableReferenceQueue, empt…
lukaszlenart Mar 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/showcase/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
</dependency>

<dependency>
<groupId>org.sitemesh</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ public class Component {
*/
protected static ConcurrentMap<Class<?>, Collection<String>> standardAttributesMap = new ConcurrentHashMap<>();

/**
* Clears the standard attributes cache to prevent classloader memory leaks during hot redeployment.
* The cache uses Class keys which pin the webapp classloader.
*/
public static void clearStandardAttributesMap() {
standardAttributesMap.clear();
}

protected boolean devMode = false;
protected boolean escapeHtmlBody = false;
protected ValueStack stack;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,10 @@ public PackageConfig removePackageConfig(String packageName) {
public void destroy() {
packageContexts.clear();
loadedFileNames.clear();
if (container != null) {
container.destroy();
container = null;
}
}

@Override
Expand All @@ -266,8 +270,7 @@ public void rebuildRuntimeConfiguration() {
*/
@Override
public synchronized List<PackageProvider> reloadContainer(List<ContainerProvider> providers) throws ConfigurationException {
packageContexts.clear();
loadedFileNames.clear();
destroy();
List<PackageProvider> packageProviders = new ArrayList<>();

ContainerProperties props = new ContainerProperties();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* 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.struts2.dispatcher;

import org.apache.struts2.components.Component;

/**
* Clears {@link Component}'s static standard attributes cache to prevent
* classloader leaks on hot redeploy.
*
* @since 7.2.0
*/
public class ComponentCacheDestroyable implements InternalDestroyable {

@Override
public void destroy() {
Component.clearStandardAttributesMap();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,65 @@

import org.apache.struts2.inject.Container;

import java.util.concurrent.atomic.AtomicLong;

/**
* Simple class to hold Container instance per thread to minimise number of attempts
* to read configuration and build each time a new configuration.
* Per-thread cache for the Container instance, minimising repeated reads from
* {@link org.apache.struts2.config.ConfigurationManager}.
* <p>
* As ContainerHolder operates just per thread (which means per request) there is no need
* to check if configuration changed during the same request. If changed between requests,
* first call to store Container in ContainerHolder will be with the new configuration.
* WW-5537: Uses a ThreadLocal for per-request isolation with an AtomicLong generation
* counter for cross-thread invalidation during app undeploy. When
* {@link #invalidateAll()} is called, all threads see the updated generation on their
* next {@link #get()} and return {@code null}, forcing a fresh read from
* ConfigurationManager. This prevents classloader leaks caused by idle pool threads
* retaining stale Container references after hot redeployment.
*/
class ContainerHolder {

private static final ThreadLocal<Container> instance = new ThreadLocal<>();
private static final ThreadLocal<CachedContainer> instance = new ThreadLocal<>();

/**
* Incremented on each {@link #invalidateAll()} call. Threads compare their cached
* generation against this value to detect staleness.
*/
private static final AtomicLong generation = new AtomicLong();

public static void store(Container newInstance) {
instance.set(newInstance);
instance.set(new CachedContainer(newInstance, generation.get()));
}

public static Container get() {
return instance.get();
CachedContainer cached = instance.get();
if (cached == null) {
return null;
}
if (cached.generation() != generation.get()) {
instance.remove();
return null;
}
return cached.container();
}

/**
* Clears the current thread's cached container reference.
* Used for per-request cleanup.
*/
public static void clear() {
instance.remove();
}

/**
* Invalidates all threads' cached container references by advancing the generation
* counter. Each thread will detect the stale generation on its next {@link #get()}
* call and clear its own ThreadLocal. Also clears the calling thread immediately.
* <p>
* Used during application undeploy ({@link Dispatcher#cleanup()}) to ensure idle
* pool threads do not pin the webapp classloader via retained Container references.
*/
public static void invalidateAll() {
generation.incrementAndGet();
instance.remove();
}

private record CachedContainer(Container container, long generation) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* 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.struts2.dispatcher;

import jakarta.servlet.ServletContext;

/**
* Extension of {@link InternalDestroyable} for components that require
* {@link ServletContext} during cleanup (e.g. clearing servlet-scoped caches).
*
* &lt;p&gt;During {@link Dispatcher#cleanup()}, the discovery loop checks each
* {@code InternalDestroyable} bean: if it implements this subinterface,
* {@link #destroy(ServletContext)} is called instead of {@link #destroy()}.&lt;/p&gt;
*
* @since 7.2.0
* @see InternalDestroyable
* @see Dispatcher#cleanup()
*/
public interface ContextAwareDestroyable extends InternalDestroyable {

/**
* Releases state that requires access to the {@link ServletContext}.
*
* @param servletContext the current servlet context, may be {@code null}
* if the Dispatcher was created without one
*/
void destroy(ServletContext servletContext);

/**
* Default no-op — {@link Dispatcher} calls
* {@link #destroy(ServletContext)} instead when it recognises this type.
*/
@Override
default void destroy() {
// no-op: context-aware variant is the real entry point
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* 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.struts2.dispatcher;

import org.apache.struts2.util.DebugUtils;

/**
* Clears {@link DebugUtils}'s static logged-keys cache to prevent memory leaks
* during hot redeployment.
*
* @since 7.2.0
*/
public class DebugUtilsCacheDestroyable implements InternalDestroyable {

@Override
public void destroy() {
DebugUtils.clearCache();
}
}
105 changes: 84 additions & 21 deletions core/src/main/java/org/apache/struts2/dispatcher/Dispatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -441,37 +441,78 @@ public void setThreadAllowlist(ThreadAllowlist threadAllowlist) {
* Releases all instances bound to this dispatcher instance.
*/
public void cleanup() {
// clean up ObjectFactory
destroyObjectFactory();

// clean up Dispatcher itself for this thread
instance.remove();
servletContext.setAttribute(StrutsStatics.SERVLET_DISPATCHER, null);

destroyDispatcherListeners();

destroyInterceptors();

destroyInternalBeans();

// WW-5537: Invalidate all threads' cached Container references to prevent
// classloader leaks from idle pool threads retaining stale references after undeploy.
ContainerHolder.invalidateAll();

//cleanup action context
ActionContext.clear();

// clean up configuration
configurationManager.destroyConfiguration();
configurationManager = null;
}

/**
* Destroys the {@link ObjectFactory} if it implements {@link ObjectFactoryDestroyable}.
*
* @since 7.2.0
*/
protected void destroyObjectFactory() {
if (objectFactory == null) {
LOG.warn("Object Factory is null, something is seriously wrong, no clean up will be performed");
return;
}
if (objectFactory instanceof ObjectFactoryDestroyable) {
if (objectFactory instanceof ObjectFactoryDestroyable ofd) {
try {
((ObjectFactoryDestroyable) objectFactory).destroy();
ofd.destroy();
} catch (Exception e) {
// catch any exception that may occur during destroy() and log it
LOG.error("Exception occurred while destroying ObjectFactory [{}]", objectFactory.toString(), e);
}
}
}

// clean up Dispatcher itself for this thread
instance.remove();
servletContext.setAttribute(StrutsStatics.SERVLET_DISPATCHER, null);

// clean up DispatcherListeners
/**
* Notifies all registered {@link DispatcherListener}s that this dispatcher
* is being destroyed, then clears the listener list.
*
* @since 7.2.0
*/
protected void destroyDispatcherListeners() {
if (!dispatcherListeners.isEmpty()) {
for (DispatcherListener l : dispatcherListeners) {
l.dispatcherDestroyed(this);
}
// WW-5537: Clear the static listener list to release references that may
// pin the webapp classloader after undeploy.
dispatcherListeners.clear();
}
}

// clean up all interceptors by calling their destroy() method
/**
* Destroys all interceptors registered in the current configuration.
*
* @since 7.2.0
*/
protected void destroyInterceptors() {
Set<Interceptor> interceptors = new HashSet<>();
Collection<PackageConfig> packageConfigs = configurationManager.getConfiguration().getPackageConfigs().values();
for (PackageConfig packageConfig : packageConfigs) {
for (Object config : packageConfig.getAllInterceptorConfigs().values()) {
if (config instanceof InterceptorStackConfig) {
for (InterceptorMapping interceptorMapping : ((InterceptorStackConfig) config).getInterceptors()) {
if (config instanceof InterceptorStackConfig isc) {
for (InterceptorMapping interceptorMapping : isc.getInterceptors()) {
interceptors.add(interceptorMapping.getInterceptor());
}
}
Expand All @@ -480,16 +521,38 @@ public void cleanup() {
for (Interceptor interceptor : interceptors) {
interceptor.destroy();
}
}

// Clear container holder when application is unloaded / server shutdown
ContainerHolder.clear();

//cleanup action context
ActionContext.clear();

// clean up configuration
configurationManager.destroyConfiguration();
configurationManager = null;
/**
* Discovers and invokes all {@link InternalDestroyable} beans registered
* in the container, clearing static caches and stopping daemon threads
* to prevent classloader leaks during hot redeployment (WW-5537).
*
* <p>Beans implementing {@link ContextAwareDestroyable} receive the
* {@link jakarta.servlet.ServletContext} via
* {@link ContextAwareDestroyable#destroy(jakarta.servlet.ServletContext)}.</p>
*
* @since 7.2.0
*/
protected void destroyInternalBeans() {
if (configurationManager != null && configurationManager.getConfiguration() != null) {
Container container = configurationManager.getConfiguration().getContainer();
Set<String> destroyableNames = container.getInstanceNames(InternalDestroyable.class);
for (String name : destroyableNames) {
try {
InternalDestroyable destroyable = container.getInstance(InternalDestroyable.class, name);
if (destroyable instanceof ContextAwareDestroyable cad) {
cad.destroy(servletContext);
} else {
destroyable.destroy();
}
} catch (Exception e) {
LOG.warn("Error during internal cleanup [{}]", name, e);
}
}
} else {
LOG.warn("ConfigurationManager is null during cleanup, InternalDestroyable beans will not be invoked");
}
}

private void init_FileManager() throws ClassNotFoundException {
Expand Down
Loading
Loading