Skip to content

Commit 3dac274

Browse files
committed
Avoid synchronization for delegate initialization
Closes gh-33656
1 parent 6b97559 commit 3dac274

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

spring-web/src/main/java/org/springframework/web/filter/DelegatingFilterProxy.java

+14-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2023 the original author or authors.
2+
* Copyright 2002-2024 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
1717
package org.springframework.web.filter;
1818

1919
import java.io.IOException;
20+
import java.util.concurrent.locks.Lock;
21+
import java.util.concurrent.locks.ReentrantLock;
2022

2123
import jakarta.servlet.Filter;
2224
import jakarta.servlet.FilterChain;
@@ -97,7 +99,7 @@ public class DelegatingFilterProxy extends GenericFilterBean {
9799
@Nullable
98100
private volatile Filter delegate;
99101

100-
private final Object delegateMonitor = new Object();
102+
private final Lock delegateLock = new ReentrantLock();
101103

102104

103105
/**
@@ -226,7 +228,8 @@ protected boolean isTargetFilterLifecycle() {
226228

227229
@Override
228230
protected void initFilterBean() throws ServletException {
229-
synchronized (this.delegateMonitor) {
231+
this.delegateLock.lock();
232+
try {
230233
if (this.delegate == null) {
231234
// If no target bean name specified, use filter name.
232235
if (this.targetBeanName == null) {
@@ -241,6 +244,9 @@ protected void initFilterBean() throws ServletException {
241244
}
242245
}
243246
}
247+
finally {
248+
this.delegateLock.unlock();
249+
}
244250
}
245251

246252
@Override
@@ -250,7 +256,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
250256
// Lazily initialize the delegate if necessary.
251257
Filter delegateToUse = this.delegate;
252258
if (delegateToUse == null) {
253-
synchronized (this.delegateMonitor) {
259+
this.delegateLock.lock();
260+
try {
254261
delegateToUse = this.delegate;
255262
if (delegateToUse == null) {
256263
WebApplicationContext wac = findWebApplicationContext();
@@ -262,6 +269,9 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
262269
}
263270
this.delegate = delegateToUse;
264271
}
272+
finally {
273+
this.delegateLock.unlock();
274+
}
265275
}
266276

267277
// Let the delegate perform the actual doFilter operation.

0 commit comments

Comments
 (0)