Quick revision
The short answer
The static list belongs to the class, not to any test, and it lives as long as the class loader, which in a test run is usually the whole JVM. The first test leaves entries in it, the second test starts with them, so the result depends on which tests run together and in what order. The fix is to avoid mutable static state, normally by making the cache an instance field and injecting it, and, only when the static cannot be removed yet, by resetting it before each test.
What to remember
In this answer, we saw that a static field belongs to the class and lives as long as the class loader, which in a test run is the whole JVM, so a static mutable list carries data from one test to the next and makes results depend on order. The proper fix is to remove the mutable static state by making the cache an instance field or an injected bean, with a reset in @BeforeEach only as a temporary patch. We also saw that the same field leaks memory and races in production, while static final fields holding immutable values are perfectly safe.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The static list belongs to the class, not to any test, and it lives as long as the class loader, which in a test run is usually the whole JVM. The first test leaves entries in it, the second test starts with them, so the result depends on which tests run together and in what order. The fix is to avoid mutable static state, normally by making the cache an instance field and injecting it, and, only when the static cannot be removed yet, by resetting it before each test.
Why this question is asked
Tests that pass alone and fail together are one of the most frustrating kinds of failure, because every test looks correct when we read it. Shared static state is the most common cause, and the same state that pollutes tests also leaks memory and races between threads in production. Interviewers ask this to see whether we recognise the pattern and fix the design rather than just patching the tests. In this answer, we will recap how static fields live, reproduce the failure, see why test order matters, fix it properly, and look at what the same field does in a running server.
1A Quick Recap: Where a Static Field Lives
An instance field belongs to one object: every new object gets its own copy. A static field belongs to the class, and there is exactly one copy per class loader. It is created when the class is initialized and stays until the class loader is discarded.
Test frameworks such as JUnit create a new instance of the test class for each test method by default, so instance fields start fresh. But all the tests in a run usually share one JVM and one class loader. Maven Surefire and Gradle reuse a forked JVM for many test classes by default. So a static field set by one test is still there for every test that runs afterwards, in any test class.
2Reproducing the Failure
Here is the class and two tests that each pass on their own.
6 messages in order. Play them, or step through them one at a time.
The list outlives the first test, so the second one starts with leftover data.
Each test creates a new TagService, and that looks like isolation. It is not, because both TagService objects use the same static list. Notice also that a third test in another class, which uses TagService for something else, can make either of these fail, so the failure can appear or vanish when someone adds an unrelated test.
3Why Order Changes the Outcome
JUnit Jupiter runs test methods in an order that is deterministic but deliberately not obvious, and build tools may run test classes in any order, or in parallel. Run addsTwoTags first, and it passes while addsOneTag fails with 3 instead of 1. Run them in separate JVMs, and both pass. Each test silently depends on what ran before it, which is exactly what a test must not do.
Running a test in the IDE usually runs it alone, so the developer sees green, and the CI run of the whole suite sees red. When we see this pattern, the first thing to look for is static fields, static singletons and other global state such as system properties, the default time zone or a static clock that tests change.
4The Proper Fix: Remove the Mutable Static State
The cache does not need to be static. If it is an instance field, every TagService has its own, and every test gets a fresh one. If several parts of the application must share one cache, that is a job for dependency injection: the cache is a singleton bean, and the code receives it.
Notice that we also replaced ArrayList with a thread-safe list, because a shared cache is accessed from several request threads in production. In a real service, a bounded cache library such as Caffeine, which can evict old entries, is usually the better choice.
5When the Static Cannot Go Yet
Sometimes the static field is in code we cannot change this week, such as a legacy class or a third-party library. Then the tests must reset it explicitly before each test, so each one starts from a known state.
This works, but it is a patch. Every test class that touches TagService, directly or through other code, must remember the reset, and parallel test execution can still break it because two tests may use the list at the same time. We should treat it as a temporary measure and track the real fix.
6What the Same Field Does in Production
The same mutable static collection causes two more problems in a running server. It is a memory leak: nothing ever removes entries, the static field keeps the list reachable for the life of the application, and after millions of requests it holds millions of strings. In an application server that redeploys applications, a static reference can even keep the whole old class loader alive.
It is also a race. ArrayList is not thread-safe, and two request threads calling add at the same time can lose an entry or corrupt the list's internal state.
None of this applies to static final fields holding immutable values, such as static final int MAX_TAGS = 50 or static final List<String> RESERVED = List.of("admin", "root"). They never change, so there is nothing to leak between tests or threads. Note that static final alone is not enough: static final List<String> cache = new ArrayList<>() has the same problem, because final protects the reference, not the list.
7Follow-up questions
Would running each test class in its own JVM fix it?
It hides it. Forking a new JVM per test class, with Surefire's reuseForks=false for example, gives each class fresh statics, but tests within one class still share them, the build becomes much slower, and the production problems remain. It is useful for finding which tests are affected, not as a fix.
How do you find which test pollutes which?
Run the failing test together with one other test class at a time, or bisect the suite, until the pair that fails is found. Some tools automate this. Then look at what the polluting test leaves behind: static fields, system properties, files or database rows.
Do Spring tests have a similar problem?
Yes, with the application context. Spring's test framework caches contexts between test classes with the same configuration, so singleton beans are shared across those classes. A test that changes a bean's state should reset it or use @DirtiesContext, which forces a new context at the cost of slower tests.
8Conclusion
In this answer, we saw that a static field belongs to the class and lives as long as the class loader, which in a test run is the whole JVM, so a static mutable list carries data from one test to the next and makes results depend on order. The proper fix is to remove the mutable static state by making the cache an instance field or an injected bean, with a reset in @BeforeEach only as a temporary patch. We also saw that the same field leaks memory and races in production, while static final fields holding immutable values are perfectly safe.
Open with
The cache is static, so it belongs to the class rather than to any TagService object, and it lives as long as the class loader. In a test run that is usually the whole JVM, since JUnit, Surefire and Gradle reuse the same JVM across tests.
Then, if they want more
Each test creates a new TagService, which looks isolated, but they all share the one list. So the first test leaves an entry behind and the second sees three items instead of two. Running alone, each passes; together, the result depends on order, which JUnit does not make obvious and which can change when someone adds an unrelated test.
The proper fix is to get rid of the mutable static state. I would make the cache an instance field injected through the constructor, so every test gets a fresh one, and in Spring the shared instance becomes a singleton bean. Since it is shared across request threads, it should also be thread-safe, or better, a bounded cache like Caffeine.
If I cannot change the class yet, I clear it in a BeforeEach method as a temporary patch.
I would also point out that the same field leaks memory in production, because nothing ever evicts entries, and races, because ArrayList is not thread-safe. static final with an immutable value, like List.of, is fine, but static final on a mutable list is not.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Two tests pass alone but fail when run together. Both use a class with static...": https://scrivio-interview-library.netlify.app/java/classes-and-objects/93bfa23f00/