Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A test uses assertTimeoutPreemptively around a call to a @Transactional Spring service and the database changes are not rolled back as expected. Why?

assertTimeoutPreemptively runs the code under test in a different thread so that it can abandon it when time runs out. Spring's test-managed transaction is bound to the test thread through a ThreadLocal, so the service call in the new thread does not join it: the @Transactional service starts and commits its own transaction, and the test's rollback has nothing to undo. The fix is to use assertTimeout, which runs in the same thread but does not abort, or to test the timeout differently.

Why this question is asked

This is a bug that wastes hours because everything looks correct: the test class is @Transactional, the service is @Transactional, and yet rows stay in the database after the test and break other tests. Interviewers like it because the answer requires knowing how two separate tools work, JUnit's timeout assertions and Spring's transaction binding, and how they interact. In this answer, we will recap how Spring rolls back test transactions, see how assertTimeoutPreemptively runs code, follow the call to see why the rollback misses it, and look at the fixes and the other ThreadLocal state that has the same problem.

1A Quick Recap of Test Transactions in Spring

When a Spring test class or method is annotated with @Transactional, the Spring TestContext framework starts a transaction before each test and rolls it back afterwards. Anything the test writes to the database disappears, so tests do not leave data behind.

The important detail is where Spring keeps the current transaction. TransactionSynchronizationManager stores the transaction's resources, such as the database connection, in ThreadLocal variables. A ThreadLocal is a variable that has a separate value for each thread, so the transaction belongs to the thread that started it. When a @Transactional service method runs with the default REQUIRED propagation, it asks: is there a transaction on my thread? If yes, it joins it; if not, it starts a new one and commits it at the end.

2How assertTimeoutPreemptively Runs the Code

JUnit has two timeout assertions. assertTimeout runs the executable in the calling thread, waits for it to finish, and then fails if it took too long. It cannot stop slow code; it only measures it. assertTimeoutPreemptively is different: to be able to abort the code when the time is up, it submits the executable to a separate thread and waits on it with a deadline. If the deadline passes, it stops waiting and fails the test.

That is the whole cause. The code we pass to assertTimeoutPreemptively does not run on the test thread.

Java
@SpringBootTest
@Transactional // test transaction, rolled back after each test
class TransferTest {
@Autowired TransferService service; // service methods are @Transactional
@Autowired AccountRepository accounts;
@Test void transfersQuickly() {
assertTimeoutPreemptively(Duration.ofSeconds(2),
() -> service.transfer("A", "B", new BigDecimal("10.00")));
// System.out.println(Thread.currentThread().getName()) inside the lambda
// prints a JUnit timeout thread, not "main"
}
}
// After the test: the transfer rows are still in the database

3Why the Rollback Misses the Changes

Now we can follow the call. The test thread has a transaction that Spring will roll back. The lambda runs on another thread, where TransactionSynchronizationManager finds nothing, because the ThreadLocal values belong to the test thread. So the @Transactional transfer method starts a brand-new transaction on the worker thread, does its updates, and commits. When the test ends, Spring rolls back the test transaction, which never contained those updates. The data stays.

Notice that the service was working exactly as designed. The test simply ran it outside the transaction it thought it was in. If the service were not @Transactional at all, the effect could be worse: the repository calls would run with auto-commit, each statement committed on its own.

Step throughThe service runs outside the test transaction
Test threadTimeout threadTransferServiceDatabase
begin test transaction (bound to test thread)
assertTimeoutPreemptively: run lambda here
transfer(A, B, 10.00)
no transaction on this thread: begin a new one
update balances, commit
lambda finished in time
roll back test transaction: nothing of ours in it

7 messages in order. Play them, or step through them one at a time.

The ThreadLocal holding the test transaction is invisible to the timeout thread.

4Fixing the Test

The simplest fix is to use assertTimeout instead. It runs the lambda on the test thread, so the service joins the test transaction and the rollback works. The trade-off is that it cannot abort a hanging call; if the code runs for a minute, the test waits a minute and then fails. For most tests that is acceptable, and a build-level timeout catches real hangs.

Java
@Test void transfersQuickly() {
assertTimeout(Duration.ofSeconds(2),
() -> service.transfer("A", "B", new BigDecimal("10.00"))); // same thread: rolled back
}
// Or JUnit's @Timeout, whose default mode also runs on the same thread
@Test @Timeout(value = 2, unit = TimeUnit.SECONDS)
void transfersQuicklyAnnotated() { service.transfer("A", "B", new BigDecimal("10.00")); }

Another option is to design the timeout differently. A timing check on a transactional database call is often not a unit-level concern at all; it belongs in a performance test. If we really need preemptive aborting, we accept that the code runs in its own transaction and clean up explicitly, for example with @Sql scripts or by deleting the rows in @AfterEach. Check your JUnit version for the thread mode options of @Timeout, because the separate-thread mode has the same problem.

5Other ThreadLocal State With the Same Problem

The transaction is only one example. Anything Spring or our code keeps in a ThreadLocal is missing on the timeout thread. Spring Security's SecurityContextHolder uses a ThreadLocal by default, so a test with @WithMockUser that calls a secured method inside assertTimeoutPreemptively gets an authentication error. The logging MDC, the mapped diagnostic context where we keep request ids for log lines, is per thread too, so log lines from the lambda lose their ids. Request-scoped beans and locale context behave the same way.

So the rule to remember is that preemptive timeouts change threads, and any per-thread context does not follow.

6Follow-up questions

How would you confirm this diagnosis?

Print Thread.currentThread().getName() inside the lambda and outside it, and print TransactionSynchronizationManager.isActualTransactionActive() inside the lambda before calling the service. On the timeout thread it prints false, which confirms there is no test transaction there. Checking the database after the test, the committed rows confirm the rest.

Does @Transactional on the test method change anything?

No. Whether the annotation is on the class or the method, the test transaction is bound to the test thread, and the code in the preemptive lambda still runs on another thread without it.

Can the code in a timed-out preemptive assertion keep running?

Yes. JUnit interrupts the worker thread and stops waiting, but if the code ignores interrupts, for example a blocking JDBC call, it may keep running in the background and even commit after the test has failed. That is another reason to avoid preemptive timeouts around database work.

7Conclusion

In this answer, we saw that Spring binds test transactions to the test thread with ThreadLocals, while assertTimeoutPreemptively runs its lambda on another thread so it can abort it. The service therefore starts and commits its own transaction, and the test's rollback misses it. assertTimeout or the same-thread @Timeout keeps the code on the test thread, and other per-thread state, such as the security context and MDC, has the same pitfall.

What to say in the interviewAbout 80 seconds aloud

Open with

The cause is that assertTimeoutPreemptively runs the lambda in a different thread, because that is the only way it can abandon the code when the time is up.

Then, if they want more

Spring's test transaction lives in ThreadLocals through TransactionSynchronizationManager, so it belongs to the test thread. When the service is called on the timeout thread, it finds no transaction, starts its own with REQUIRED propagation and commits it. Then the test ends, Spring rolls back the test transaction, which never contained those changes, and the rows stay in the database.

I would confirm it by printing the thread name and isActualTransactionActive inside the lambda. The fix is to use assertTimeout, which runs in the same thread and measures the time but cannot abort, or @Timeout in its default same-thread mode, so the service joins the test transaction and gets rolled back.

If I really need to abort a hang, I accept the separate transaction and clean up explicitly, or I move the timing check into a performance test. The same thing breaks other ThreadLocal state: the Spring Security context from @WithMockUser, MDC values for logging and request-scoped beans all disappear on the other thread.

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
JUnit user guide
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 "A test uses assertTimeoutPreemptively around a call to a @Transactional Spring service...": https://scrivio-interview-library.netlify.app/java/junit/0cbf80507e/