Skip to content

Commit fbfad86

Browse files
committed
Further improve thread safety for attributes in DefaultTestContext
Issue: SPR-5863
1 parent 5755b67 commit fbfad86

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

spring-test/src/main/java/org/springframework/test/context/support/DefaultTestContext.java

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public class DefaultTestContext implements TestContext {
4141

4242
private static final long serialVersionUID = -5827157174866681233L;
4343

44-
private final Map<String, Object> attributes = new ConcurrentHashMap<>(0);
44+
private final Map<String, Object> attributes = new ConcurrentHashMap<>(4);
4545

4646
private final CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate;
4747

@@ -58,15 +58,17 @@ public class DefaultTestContext implements TestContext {
5858

5959
/**
6060
* <em>Copy constructor</em> for creating a new {@code DefaultTestContext}
61-
* based on the immutable state and <em>attributes</em> of the supplied context.
62-
*
63-
* <p><em>Immutable state</em> includes all arguments supplied to
64-
* {@link #DefaultTestContext(Class, MergedContextConfiguration, CacheAwareContextLoaderDelegate)}.
61+
* based on the <em>attributes</em> and immutable state of the supplied context.
62+
* <p><em>Immutable state</em> includes all arguments supplied to the
63+
* {@linkplain #DefaultTestContext(Class, MergedContextConfiguration,
64+
* CacheAwareContextLoaderDelegate) standard constructor}.
65+
* @throws NullPointerException if the supplied {@code DefaultTestContext}
66+
* is {@code null}
6567
*/
6668
public DefaultTestContext(DefaultTestContext testContext) {
6769
this(testContext.testClass, testContext.mergedContextConfiguration,
6870
testContext.cacheAwareContextLoaderDelegate);
69-
testContext.attributes.forEach(this.attributes::put);
71+
this.attributes.putAll(testContext.attributes);
7072
}
7173

7274
/**
@@ -144,11 +146,13 @@ public void updateState(Object testInstance, Method testMethod, Throwable testEx
144146
@Override
145147
public void setAttribute(String name, Object value) {
146148
Assert.notNull(name, "Name must not be null");
147-
if (value != null) {
148-
this.attributes.put(name, value);
149-
}
150-
else {
151-
removeAttribute(name);
149+
synchronized (this.attributes) {
150+
if (value != null) {
151+
this.attributes.put(name, value);
152+
}
153+
else {
154+
this.attributes.remove(name);
155+
}
152156
}
153157
}
154158

@@ -172,7 +176,9 @@ public boolean hasAttribute(String name) {
172176

173177
@Override
174178
public String[] attributeNames() {
175-
return this.attributes.keySet().stream().toArray(String[]::new);
179+
synchronized (this.attributes) {
180+
return this.attributes.keySet().stream().toArray(String[]::new);
181+
}
176182
}
177183

178184

0 commit comments

Comments
 (0)