Skip to content

Race condition affecting performance in AbstractJaxb2HttpMessageConverter - JAXBContext creation #23879

Closed
@gjd6640

Description

@gjd6640

Hello. I saw this issue recently and wanted to share it with you in hopes that you can tweak things to prevent others from suffering through the troubleshooting that we just did.

Here'a [a LINK|https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/http/converter/xml/AbstractJaxb2HttpMessageConverter.java] to the source code in question.

When the code linked above's "getJaxbContext" method is called concurrently with a Jaxb type that's not already initialized in its "jaxbContexts" map we've experienced that many threads spend a lot of time on line 113's JAXBContext.newInstance() call. It appears that many threads are executing the "JAXBContext jaxbContext = this.jaxbContexts.get(clazz);" line (line 110) before any thread has been able to get to the "jaxbContexts.putIfAbsent" step.

I've attached a screenshot of a JProfiler performance profile demonstrating that the time is spent in this code. I used sampling mode instead of dynamic to minimize profiling overhead.

I think this issue can be addressed by replacing several lines of code with a single line of code that leverages ConcurrentMap's computeIfAbsent method. That method works to fetch the value from the map and on a "miss" creates the needed object, puts it in the map, and returns it.

Priority-wide this is something that may not affect a lot of users. It did take us a while to figure out why our performance was terrible and while the workaround of "priming the pump" once before going concurrent does work it looks like this is best addressed in this code as doing so will simplify the code and prevent others from suffering from this "happens once for each JVM startup, then goes away" performance degradation.

Affected versions: We're using "spring-web-5.1.1.RELEASE". I suspect that this is probably present in all reasonably-current versions.

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)status: backportedAn issue that has been backported to maintenance branchestype: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions