Make ApplicationContextRequestMatcher and subclasses thread-safe

Previously, when performing lazy initialisation of the context,
ApplicationContextRequestMatcher assigned the context field before it
called initialized. The context being non-null is used as the signal
that it’s ok to call a subclass’s matches method. If one thread checks
for a non-null context in between the field being assigned and
initialized being called on another thread, matches will be called
before the subclass is ready.

This commit closes the window for the race condition by only assigning
the context field once the subclass’s initialized method has been
called.

There is a secondary problem in each of the subclasses. Due to the use
of double-checked locking in ApplicationContextRequestMatcher, it’s
possible for a subclass’s matches method to be called by a thread that
has not synchronised on the context lock that’s held when initialized
is called and the delegate field is assigned. This means that the
value assigned to the field may not be visible to that thread.

This commit declares the delegate field of each
ApplicationContextRequestMatcher subclass as volatile to ensure that,
following initialisation, its value is guaranteed to be visible to
all threads.

Closes gh-12380
This commit is contained in:
Andy Wilkinson 2018-03-07 09:57:16 +00:00
parent 42629cb8ae
commit 317b51f2ad
4 changed files with 6 additions and 5 deletions

View File

@ -100,7 +100,7 @@ public final class EndpointRequest {
private final List<Object> excludes;
private RequestMatcher delegate;
private volatile RequestMatcher delegate;
private EndpointRequestMatcher() {
this(Collections.emptyList(), Collections.emptyList());

View File

@ -64,7 +64,7 @@ public final class PathRequest {
public static final class H2ConsoleRequestMatcher
extends ApplicationContextRequestMatcher<H2ConsoleProperties> {
private RequestMatcher delegate;
private volatile RequestMatcher delegate;
private H2ConsoleRequestMatcher() {
super(H2ConsoleProperties.class);

View File

@ -100,7 +100,7 @@ public final class StaticResourceRequest {
private final Set<StaticResourceLocation> locations;
private RequestMatcher delegate;
private volatile RequestMatcher delegate;
private StaticResourceRequestMatcher(Set<StaticResourceLocation> locations) {
super(ServerProperties.class);

View File

@ -69,8 +69,9 @@ public abstract class ApplicationContextRequestMatcher<C> implements RequestMatc
if (this.context == null) {
synchronized (this.contextLock) {
if (this.context == null) {
this.context = createContext(request);
initialized(this.context);
Supplier<C> createdContext = createContext(request);
initialized(createdContext);
this.context = createdContext;
}
}
}