Revise synchronized blocks

- Replace synchronized with Lock when guarding long-running operations
- Remove unnecessary synchronization in FileSystemWatcher
- Replace HashMap with ConcurrentHashMap in Restarter
- Remove unnecessary locking on AtomicBoolean in
  SpringApplicationBuilder
- Remove unnecessary locking in SimpleFormatter

Closes gh-36670
This commit is contained in:
Moritz Halbritter
2023-08-02 14:30:38 +02:00
parent 6506208d29
commit 497bbf9c2d
19 changed files with 380 additions and 150 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2012-2022 the original author or authors.
* Copyright 2012-2023 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.
@@ -22,6 +22,8 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
@@ -52,7 +54,13 @@ public class TemplateAvailabilityProviders {
private final Map<String, TemplateAvailabilityProvider> resolved = new ConcurrentHashMap<>(CACHE_LIMIT);
/**
* Map from view name resolve template view, synchronized when accessed.
* Guards access to {@link #cache}.
*/
private final Lock cacheLock = new ReentrantLock();
/**
* Map from view name resolve template view, protected by {@link #cacheLock} when
* accessed.
*/
private final Map<String, TemplateAvailabilityProvider> cache = new LinkedHashMap<>(CACHE_LIMIT, 0.75f, true) {
@@ -133,12 +141,16 @@ public class TemplateAvailabilityProviders {
}
TemplateAvailabilityProvider provider = this.resolved.get(view);
if (provider == null) {
synchronized (this.cache) {
this.cacheLock.lock();
try {
provider = findProvider(view, environment, classLoader, resourceLoader);
provider = (provider != null) ? provider : NONE;
this.resolved.put(view, provider);
this.cache.put(view, provider);
}
finally {
this.cacheLock.unlock();
}
}
return (provider != NONE) ? provider : null;
}