Skip to content

GH-1295 - Replace HashMap with ConcurrentHashMap for thread safety #1298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
package org.springframework.modulith.core;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand All @@ -37,7 +37,7 @@ public class PackageName implements Comparable<PackageName> {

public static final String DEFAULT = "<<default>>";

private static final Map<String, PackageName> PACKAGE_NAMES = new HashMap<>();
private static final Map<String, PackageName> PACKAGE_NAMES = new ConcurrentHashMap<>();

private final String name;
private final String[] segments;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
package org.springframework.modulith.test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -51,8 +51,8 @@ public class ModuleTestExecution implements Iterable<ApplicationModule> {
private static final Logger LOGGER = LoggerFactory.getLogger(ModuleTestExecution.class);
private static final ApplicationModulesFactory BOOTSTRAP;

private static Map<Class<?>, Class<?>> MODULITH_TYPES = new HashMap<>();
private static Map<Key, ModuleTestExecution> EXECUTIONS = new HashMap<>();
private static final Map<Class<?>, Class<?>> MODULITH_TYPES = new ConcurrentHashMap<>();
private static final Map<Key, ModuleTestExecution> EXECUTIONS = new ConcurrentHashMap<>();

static {

Expand Down Expand Up @@ -84,7 +84,7 @@ private ModuleTestExecution(ApplicationModuleTest annotation, ApplicationModules
this.basePackages = SingletonSupplier.of(() -> {

var moduleBasePackages = module.getBootstrapBasePackages(modules, bootstrapMode.getDepth());
var sharedBasePackages = modules.getSharedModules().stream().map(it -> it.getBasePackage());
var sharedBasePackages = modules.getSharedModules().stream().map(ApplicationModule::getBasePackage);
var extraPackages = extraIncludes.stream().map(ApplicationModule::getBasePackage);

var intermediate = Stream.concat(moduleBasePackages, extraPackages);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* Copyright 2018-2025 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.modulith.test;

import example.module.SampleTestA;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Unit tests for {@link ModuleTestExecution}.
*
* @author Yevhenii Semenov
*/
class ModuleTestExecutionUnitTests {

@Test
void concurrentAccessToExecutionCacheIsSafe() throws InterruptedException {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have checked that the test now passes and fails again when I revert ConcurrentHashMap to HashMap.

int threadCount = 10;
var startBarrier = new CyclicBarrier(threadCount);
var completionLatch = new CountDownLatch(threadCount);
var errors = Collections.synchronizedList(new ArrayList<Exception>());
var executions = new ConcurrentHashMap<Integer, ModuleTestExecution>();

var executorService = Executors.newFixedThreadPool(threadCount);
try {
for (int i = 0; i < threadCount; i++) {
int threadId = i;
executorService.submit(() -> {
try {
// Synchronize thread start for maximum contention
startBarrier.await();

// Get the execution
var execution = ModuleTestExecution.of(SampleTestA.class).get();
executions.put(threadId, execution);

} catch (Exception e) {
errors.add(e);
} finally {
completionLatch.countDown();
}
});
}

// Wait for all threads to complete
assertThat(completionLatch.await(5, TimeUnit.SECONDS))
.as("All threads should complete within 5 seconds")
.isTrue();

// Check for errors
assertThat(errors)
.as("No exceptions during concurrent access")
.isEmpty();

// Verify all threads got the same cached instance
assertThat(executions).hasSize(threadCount);
var firstExecution = executions.get(0);
assertThat(executions.values())
.allSatisfy(execution -> assertThat(execution).isSameAs(firstExecution));

} finally {
executorService.shutdown();
}
}
}