Keep the latest result in an asynchronous Swing search
Keep a slow Swing search from replacing newer results. Debounce typing, query the database on a worker thread, and check the request token on the EDT.
An older search can overwrite newer results in Swing if it finishes last. In RSIS I debounce typing, query the database on a worker thread, and check the request token on the event dispatch thread before showing a result or an error.
The example uses Java 17 and the local H2 search in RSIS
refactor-v2.
The list has to agree with the search box
Suppose I submit soup and follow it with rice soup. The second lookup can finish first. If I display everything in completion order, the first lookup can replace those results a moment later. The text field will still say rice soup, and the list will be showing a different query.
The same race can happen with a local database or an HTTP service. One query can take longer to run, and each worker posts its result to the Swing event queue. I accept callbacks from the latest submitted search and drop callbacks that carry older tokens.
Wait for a pause in typing
The search screen uses a one-shot Swing Timer with a 180 ms delay. The document listener calls debounce.restart() on every change. When typing pauses for 180 ms, the timer submits one search for the text already in the field.
1
2
Timer debounce = new Timer(180, event -> controller.changeQuery(search.text()));
debounce.setRepeats(false);
Swing calls the timer’s listener on the event dispatch thread (EDT). The listener reads the text field and passes the criteria to the controller. The controller records the request and submits the query to an executor. The worker uses SwingUtilities.invokeLater() to post its result back to the EDT.
The timer limits how often searches start. If you pause for 180 ms and type again while the first query is still running, the next search can start before the first one finishes. Java 17 Swing Timer · RSIS timer setup
Check the request token where the view changes
Each call to RequestGate.nextToken() attempts to cancel the previous future and increments its counter. The new task captures that counter value as its token. On success or failure, the callback checks the token again on the EDT.
This section of the controller checks whether a result can update the list. The full method also handles a requested page that no longer exists in the results.
1
2
3
4
if (!gate.isLatest(token)) {
return;
}
store.update(s -> s.loaded(result));
I compare the token inside the callback that updates the view. If the worker checked it before posting the callback, another search could start while that callback waited in the EDT queue. Error callbacks make the same check to keep an old failure from covering a newer result.
RSIS calls cancel(false) on database work to avoid interrupting a read from the H2 file database. A query that has already started can finish, and a callback that’s already queued can still run. Leaving the screen invalidates the token too. The pending callback then reaches the EDT with a token that can no longer update the view. Java 17 Future.cancel · RSIS request gate · RSIS search controller
The token identifies the latest submitted search. The previous lookup can still update the list while the new text waits for the timer. If the list should stop accepting old results as soon as the text changes, invalidate the token in the document listener.
Keep showing the page you already have
I show a loading skeleton on the first lookup. Once there are rows to show, I use REFRESHING and put a banner above the previous page. The banner explains why the rows may still match an earlier query. The new page replaces those rows when its query succeeds.
While the refresh runs, RSIS uses the ID of the row you click to open a restaurant. If an action depends on the rows matching the new search criteria, disable it until the results arrive. The list restoration post covers returning from a detail screen with a refresh in progress.
| Workload | Search strategy | Reason |
|---|---|---|
| Each query reads from a database or network | Debounce, run the query on a worker, and check the token on the EDT | Limits how often queries run and protects the newest result |
| Filtering a tiny in-memory list | Apply a quick filter on the EDT | The cost of scheduling work can exceed the lookup |
| Each request records a distinct user action | Track each action separately | Every action needs its own outcome |
I give searches their own token. A save operation should track its own result so routine typing in the search box can’t suppress its success or error message.
Figure 1. The list shows the previous results and a blue refresh banner while the 국밥 (rice soup) search runs.
Figure 2. I released the newer result first, then let the older request finish. The displayed rows still match the newer query.
Make the older request finish last in a test
The RSIS test holds A on a CountDownLatch. It posts B’s callback to the EDT, releases A, and waits for A to post its callback too. It waits for the EDT to finish the queued callbacks before checking that the state still holds B’s result. Canceling A before it starts could pass the same final assertion without exercising a late callback.
Run these tests from the RSIS checkout. The controller test also verifies that the previous rows stay in the state during a refresh.
1
./gradlew test --tests '*RequestGateTest' --tests '*ExploreControllerTest'
To reproduce the race on screen, use a test search function that lets you release each response on demand. Type the first query, wait for the timer to submit it, then type the second. While the second query is pending, look for the refresh banner above the previous rows. Release the second response and wait for its rows to appear before releasing the first. The list and status should still match the second query. RSIS late-completion test
- The debounce handler hands off slow work without blocking the EDT.
- The success and error callbacks both apply the token check on the EDT.
- The first lookup shows a loading skeleton. Refreshing keeps the previous rows on screen.
- The race test delivers an older callback after the latest result.