Skip to content

Commit

Permalink
Avoid synchronization for delegate initialization
Browse files Browse the repository at this point in the history
Closes gh-33656
  • Loading branch information
jhoeller committed Oct 7, 2024
1 parent 6b97559 commit 3dac274
Showing 1 changed file with 14 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -17,6 +17,8 @@
package org.springframework.web.filter;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
Expand Down Expand Up @@ -97,7 +99,7 @@ public class DelegatingFilterProxy extends GenericFilterBean {
@Nullable
private volatile Filter delegate;

private final Object delegateMonitor = new Object();
private final Lock delegateLock = new ReentrantLock();


/**
Expand Down Expand Up @@ -226,7 +228,8 @@ protected boolean isTargetFilterLifecycle() {

@Override
protected void initFilterBean() throws ServletException {
synchronized (this.delegateMonitor) {
this.delegateLock.lock();
try {
if (this.delegate == null) {
// If no target bean name specified, use filter name.
if (this.targetBeanName == null) {
Expand All @@ -241,6 +244,9 @@ protected void initFilterBean() throws ServletException {
}
}
}
finally {
this.delegateLock.unlock();
}
}

@Override
Expand All @@ -250,7 +256,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
// Lazily initialize the delegate if necessary.
Filter delegateToUse = this.delegate;
if (delegateToUse == null) {
synchronized (this.delegateMonitor) {
this.delegateLock.lock();
try {
delegateToUse = this.delegate;
if (delegateToUse == null) {
WebApplicationContext wac = findWebApplicationContext();
Expand All @@ -262,6 +269,9 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
}
this.delegate = delegateToUse;
}
finally {
this.delegateLock.unlock();
}
}

// Let the delegate perform the actual doFilter operation.
Expand Down

0 comments on commit 3dac274

Please sign in to comment.