Skip to content

MethodParameter.findParameterIndex() is not thread-safe [SPR-17534] #22066

@spring-projects-issues

Description

@spring-projects-issues

Sam Brannen opened SPR-17534 and commented

Status Quo

As discussed in #22065, org.springframework.core.MethodParameter.findParameterIndex(Parameter) is not thread-safe due to the manner in which java.lang.reflect.Executable.getParameters() is implemented in the JDK.

Proposed Solution

The following change has been verified to result in thread-safe behavior.

Whether or not we want two iterations is up for debate.

protected static int findParameterIndex(Parameter parameter) {
	Executable executable = parameter.getDeclaringExecutable();
	Parameter[] allParams = executable.getParameters();
	
	// Try first with identity checks for greater performance.
	for (int i = 0; i < allParams.length; i++) {
		if (parameter == allParams[i]) {
			return i;
		}
	}
	// Potentially try again with object equality in order to avoid race
	// conditions while accessing java.lang.reflect.Executable.getParameters().
	for (int i = 0; i < allParams.length; i++) {
		if (parameter.equals(allParams[i])) {
			return i;
		}
	}
	throw new IllegalArgumentException("Given parameter [" + parameter +
			"] does not match any parameter in the declaring executable");
}

Deliverables

  1. Ensure that MethodParameter.findParameterIndex() is thread-safe

Affects: 5.0.10, 5.1 GA

Issue Links:

Referenced from: commits 81fde5e, f0e69e0

Backported to: 5.0.11

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)status: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions