Make GenericContainer.start() and stop() thread-safe#11702
Open
remal wants to merge 1 commit intotestcontainers:mainfrom
Open
Make GenericContainer.start() and stop() thread-safe#11702remal wants to merge 1 commit intotestcontainers:mainfrom
remal wants to merge 1 commit intotestcontainers:mainfrom
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
GenericContainer.start()guards against double-start withif (containerId != null) return, butstart()is not synchronized. When two threads callstart()on the same container concurrently, both can pass the guard before either setscontainerId, creating two Docker containers for one logical dependency.This can happen when
@Testcontainersis used and the container is also started from another context. In our case, we have custom test infrastructure that handles@Containerannotations and starts containers. It does not cover all use-cases, so some test classes still need to use@Testcontainers. When both the custom infrastructure and the extension callstart()on the same container, they race.The workaround is to not annotate dependencies with
@Container, but this is not obvious to developers and error-prone.The fix adds
@Synchronizedtostart()andstop()inGenericContainerand all otherStartableimplementations that override these methods.containerIdis also madevolatilefor cross-thread visibility.