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.
@@ -18,6 +18,8 @@ package org.springframework.boot.test.autoconfigure.web.servlet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.openqa.selenium.WebDriver;
@@ -52,11 +54,17 @@ public class WebDriverScope implements Scope {
private static final String[] BEAN_CLASSES = { WEB_DRIVER_CLASS,
"org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDriverBuilder" };
/**
* Guards access to {@link #instances}.
*/
private final Lock instancesLock = new ReentrantLock();
private final Map<String, Object> instances = new HashMap<>();
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
synchronized (this.instances) {
this.instancesLock.lock();
try {
Object instance = this.instances.get(name);
if (instance == null) {
instance = objectFactory.getObject();
@@ -64,13 +72,20 @@ public class WebDriverScope implements Scope {
}
return instance;
}
finally {
this.instancesLock.unlock();
}
}
@Override
public Object remove(String name) {
synchronized (this.instances) {
this.instancesLock.lock();
try {
return this.instances.remove(name);
}
finally {
this.instancesLock.unlock();
}
}
@Override
@@ -93,7 +108,8 @@ public class WebDriverScope implements Scope {
*/
boolean reset() {
boolean reset = false;
synchronized (this.instances) {
this.instancesLock.lock();
try {
for (Object instance : this.instances.values()) {
reset = true;
if (instance instanceof WebDriver webDriver) {
@@ -102,6 +118,9 @@ public class WebDriverScope implements Scope {
}
this.instances.clear();
}
finally {
this.instancesLock.unlock();
}
return reset;
}