Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
Keep Java desktop apps responsive: why the UI thread must never block, how to run work in background threads, update components safely with EventQueue.invokeLater, and use SwingWorker's doInBackground, publish, process, done and cancel, plus JavaFX and Android equivalents.
kvi5hnuCode Sprout team member9 min readOn this page
One of the main reasons to use threads is responsiveness. In a desktop or mobile app, the user expects buttons to react and windows to repaint while the program loads a file, queries a server or crunches numbers. This article shows the threading rule behind every UI toolkit, and how Swing's SwingWorker makes background work with progress reporting and cancellation easy. The same ideas apply to JavaFX and Android.
The single UI thread
Swing, JavaFX and Android all use the same design. UI components are not thread-safe, and all UI work happens on one thread. In Swing it's the event dispatch thread (EDT), and in JavaFX the JavaFX Application Thread. On Android it's the main thread. Event handlers such as button clicks run on that thread, and so does painting.
That leads to two rules.
Rule 1: Never do slow work on the UI thread. While your handler runs, the thread can't repaint or react to clicks, and the app freezes. This is wrong:
var open = new JButton("Open");
open.addActionListener(event -> { // BAD: long-running work on the UI thread
try (var in = new Scanner(file)) {
while (in.hasNextLine()) {
String line = in.nextLine();
...
}
}
});
Hand the work to another thread instead:
open.addActionListener(event -> { // GOOD: work happens in a background thread
Runnable task = () -> {
try (var in = new Scanner(file)) {
while (in.hasNextLine()) { ... }
}
};
executor.execute(task);
});
Rule 2: Only touch UI components from the UI thread. The worker can't simply call label.setText(...). Concurrent access would corrupt the components. JavaFX and Android detect it and throw an exception, while Swing silently misbehaves. Instead, each toolkit lets you schedule a Runnable on the UI thread:
EventQueue.invokeLater(() -> label.setText(percentage + "% complete")); // Swing
Platform.runLater(() -> label.setText(...)); // JavaFX
runOnUiThread(() -> textView.setText(...)); // Android Activity
SwingUtilities.invokeLater is the same as EventQueue.invokeLater. invokeAndWait also waits until the code has run, but never call it from the EDT. It would wait for itself, so Swing refuses and throws java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread. Swing programs should even create their windows on the EDT, which is why main methods start with EventQueue.invokeLater(() -> { var frame = ...; frame.setVisible(true); }).
With CompletableFuture (article 102), the pattern fits in one expression. You compute in a pool and then continue on the UI thread by passing the toolkit's scheduler as the executor:
CompletableFuture.supplyAsync(() -> loadData(), workers)
.thenAcceptAsync(data -> table.setModel(toModel(data)), EventQueue::invokeLater);
SwingWorker
Writing progress updates and completion handling by hand is tedious. Every toolkit therefore has a helper: SwingWorker in Swing, Task/Service in JavaFX, and on Android, Kotlin coroutines or WorkManager. Android's old AsyncTask was deprecated in API level 30. You specify the long-running work, which runs on a background thread, plus progress updates and the final result handling, which run on the UI thread.
A typical background task does two kinds of UI work:
- After each unit of work, update the UI to show progress.
- When the work is finished, make a final change to the UI.
SwingWorker<T, V> produces a result of type T and progress data of type V. You subclass it and override up to three methods:
doInBackground()runs on a worker thread. It does the slow work, callspublish(v...)to report progress, and returns the result.process(List<V> chunks)runs on the EDT and receives published data. For efficiency, Swing may batch severalpublishcalls into oneprocesscall, so you get a list. Often only its last element matters.done()runs on the EDT whendoInBackgroundhas finished, whether normally, with an exception, or by cancellation. Callget()here to retrieve the result.

To start a worker, construct it and call execute(), usually from an event handler on the EDT, although that's not required. Each worker object can run only once. Make a new one for each job.
SwingWorker implements Future<T>. That gives you:
get()returns the result. It blocks, so don't call it right afterexecute. Call it indone(), where the work is known to be finished. You don't have to call it if progress data is all you need.cancel(true)interrupts the worker thread. AfterwardsisCancelled()istrue,done()still runs, andget()throwsCancellationException. Exceptions thrown bydoInBackgroundshow up asExecutionExceptionfromget().getState()returnsPENDING,STARTEDorDONE.
There's also a built-in progress property. Call setProgress(0..100) in doInBackground and listen with addPropertyChangeListener, which is ideal for driving a JProgressBar.
Example: loading a large text file
The following program has an Open menu item that loads a text file into a JTextArea in the background, and a Cancel item. While loading, Open is disabled, Cancel is enabled, and the status bar shows the current line number. At the end, the text area gets the full text and the status reads "Done" or "Cancelled". JTextArea is slow at appending, so a long book, such as a public-domain novel from Project Gutenberg, takes long enough to watch the progress.
The progress data is the line number plus the line's text, packaged as a record. The final result is the accumulated text, so the worker type is SwingWorker<StringBuilder, Progress>. Run this on a machine with a display:
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import javax.swing.*;
public class TextLoaderApp {
public static void main(String[] args) {
EventQueue.invokeLater(() -> { // build the UI on the EDT
var frame = new LoaderFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
class LoaderFrame extends JFrame {
private final JFileChooser chooser = new JFileChooser(".");
private final JTextArea textArea = new JTextArea(20, 60);
private final JLabel status = new JLabel(" ");
private final JMenuItem openItem = new JMenuItem("Open");
private final JMenuItem cancelItem = new JMenuItem("Cancel");
private Loader loader;
LoaderFrame() {
add(new JScrollPane(textArea));
add(status, BorderLayout.SOUTH);
var menu = new JMenu("File");
menu.add(openItem);
menu.add(cancelItem);
var bar = new JMenuBar();
bar.add(menu);
setJMenuBar(bar);
cancelItem.setEnabled(false);
openItem.addActionListener(e -> {
if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) return;
textArea.setText("");
openItem.setEnabled(false);
cancelItem.setEnabled(true);
loader = new Loader(chooser.getSelectedFile()); // a fresh worker per job
loader.execute();
});
cancelItem.addActionListener(e -> loader.cancel(true));
pack();
}
private record Progress(int lineNumber, String line) {}
private class Loader extends SwingWorker<StringBuilder, Progress> {
private final File file;
Loader(File file) { this.file = file; }
@Override protected StringBuilder doInBackground() throws Exception { // worker thread
var text = new StringBuilder();
int n = 0;
try (var in = new Scanner(file)) {
while (in.hasNextLine()) {
String line = in.nextLine();
text.append(line).append('\n');
publish(new Progress(++n, line));
Thread.sleep(1); // only so you have time to try Cancel
}
}
return text;
}
@Override protected void process(List<Progress> chunk) { // EDT, batched
if (isCancelled()) return;
status.setText("Line " + chunk.getLast().lineNumber());
var lines = new StringBuilder();
for (Progress p : chunk) lines.append(p.line()).append('\n');
textArea.append(lines.toString()); // one update per batch
}
@Override protected void done() { // EDT
try {
textArea.setText(get().toString());
status.setText("Done");
} catch (CancellationException ex) {
textArea.setText("");
status.setText("Cancelled");
} catch (ExecutionException ex) {
status.setText("Error: " + ex.getCause());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
cancelItem.setEnabled(false);
openItem.setEnabled(true);
}
}
}
Notice three details:
processignores all line numbers except the last one in each batch, and appends the batch with a singleappend, which keeps the slow text area from becoming the bottleneck.- The
Thread.sleep(1)exists only so you can test cancellation. Remove it and a long novel loads almost instantly, in just a few batched UI updates. - The sleep also makes cancellation prompt, because
cancel(true)interrupts the worker andsleepreacts by throwingInterruptedException. Without a blocking call, a loop that never checksisCancelled()keeps running in the background, althoughdone()still reports "Cancelled".
JavaFX and Android in brief
- JavaFX
Task<V>overridescall(), which runs in the background. Inside it,updateProgress(done, total)andupdateMessage(text)update the observableprogressandmessageproperties on the FX thread. The callbackssetOnSucceeded,setOnFailedandsetOnCancelledrun on the FX thread, and you start the task withnew Thread(task).start()or an executor. A progress bar binds withbar.progressProperty().bind(task.progressProperty()). - Android uses Kotlin coroutines (
withContext(Dispatchers.IO) { ... }) in modern code. Java code uses anExecutorplusHandler(Looper.getMainLooper()).post(...), orWorkManagerfor work that must survive the app being closed.
A complete example
A runnable example can't open a window here, so the demo runs SwingWorker in headless mode. That's enough to verify the threading. doInBackground runs off the EDT, while process and done run on it. The demo also shows the PENDING/STARTED/DONE states, the progress property, cancellation (with a latch holding the worker so the timing is deterministic), and the general "compute in a pool, continue on the UI thread" pattern with CompletableFuture.
import java.awt.EventQueue;
import java.util.*;
import java.util.concurrent.*;
import javax.swing.SwingWorker;
public class Solution {
record Progress(int lineNumber, String line) {}
/** Reads lines in the background, reports progress, finishes on the event dispatch thread. */
static class LineLoader extends SwingWorker<StringBuilder, Progress> {
private final List<String> source;
private final CountDownLatch gate; // lets the demo pause the worker deterministically
final StringBuilder status = new StringBuilder();
final CountDownLatch finished = new CountDownLatch(1);
volatile int lastReported;
volatile boolean processOnEdt = true;
volatile boolean backgroundOnEdt;
LineLoader(List<String> source, CountDownLatch gate) { this.source = source; this.gate = gate; }
@Override protected StringBuilder doInBackground() throws Exception {
backgroundOnEdt = EventQueue.isDispatchThread();
var text = new StringBuilder();
int n = 0;
for (String line : source) {
if (n == 2) gate.await(); // pause after two lines
n++;
text.append(line).append('\n');
publish(new Progress(n, line)); // queued for process() on the EDT
setProgress(100 * n / source.size());
}
return text;
}
@Override protected void process(List<Progress> chunk) { // runs on the EDT, possibly batched
if (!EventQueue.isDispatchThread()) processOnEdt = false;
if (isCancelled()) return;
lastReported = chunk.getLast().lineNumber();
}
@Override protected void done() { // runs on the EDT
try {
StringBuilder result = get();
status.append("Done: ").append(result.toString().lines().count()).append(" lines");
} catch (CancellationException e) {
status.append("Cancelled");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
status.append("Error: ").append(e.getCause().getMessage());
}
status.append(" (done on EDT? ").append(EventQueue.isDispatchThread()).append(')');
finished.countDown();
}
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true"); // no window needed for this demo
var lines = new ArrayList<String>();
for (int i = 1; i <= 500; i++) lines.add("line " + i);
System.out.println("-- a worker that runs to completion --");
var open = new CountDownLatch(0);
var loader = new LineLoader(lines, open);
var progressEvents = Collections.synchronizedList(new ArrayList<Integer>());
loader.addPropertyChangeListener(e -> {
if ("progress".equals(e.getPropertyName())) progressEvents.add((Integer) e.getNewValue());
});
System.out.println(" state before execute: " + loader.getState());
EventQueue.invokeLater(loader::execute); // typically started from an event handler
loader.finished.await();
for (int i = 0; i < 200 && (loader.lastReported < lines.size() || !progressEvents.contains(100)); i++)
Thread.sleep(10); // process() calls are coalesced and may arrive after done()
System.out.println(" doInBackground ran on EDT? " + loader.backgroundOnEdt);
System.out.println(" " + loader.status);
System.out.println(" state after: " + loader.getState() + ", last reported line: " + loader.lastReported
+ ", process always on EDT: " + loader.processOnEdt);
System.out.println(" progress reached 100: " + progressEvents.contains(100));
System.out.println("-- cancelling a worker --");
var gate = new CountDownLatch(1);
var slow = new LineLoader(lines, gate);
slow.execute();
while (slow.getState() != SwingWorker.StateValue.STARTED) Thread.sleep(5);
System.out.println(" cancel(true): " + slow.cancel(true));
slow.finished.await();
System.out.println(" " + slow.status + ", isCancelled: " + slow.isCancelled());
System.out.println("-- the general pattern: work elsewhere, update on the UI thread --");
ExecutorService ui = Executors.newSingleThreadExecutor(r -> new Thread(r, "ui-thread"));
ExecutorService workers = Executors.newFixedThreadPool(2);
Executor onUi = ui::execute; // stands in for EventQueue::invokeLater or Platform::runLater
String shown = CompletableFuture
.supplyAsync(() -> lines.stream().mapToInt(String::length).sum(), workers)
.thenApplyAsync(total -> "label text = " + total + " chars, set on "
+ Thread.currentThread().getName(), onUi)
.join();
System.out.println(" " + shown);
workers.shutdown();
ui.shutdown();
}
}
-- a worker that runs to completion --
state before execute: PENDING
doInBackground ran on EDT? false
Done: 500 lines (done on EDT? true)
state after: DONE, last reported line: 500, process always on EDT: true
progress reached 100: true
-- cancelling a worker --
cancel(true): true
Cancelled (done on EDT? true), isCancelled: true
-- the general pattern: work elsewhere, update on the UI thread --
label text = 3892 chars, set on ui-thread
Common questions
Why does my Swing window freeze while a button handler runs?
The handler runs on the event dispatch thread, which also repaints the window and processes clicks. While the handler is busy, nothing else happens. Move slow work to a SwingWorker or another thread.
How do I update a label from a background thread?
Schedule the update on the UI thread: SwingUtilities.invokeLater(() -> label.setText(text)) in Swing, Platform.runLater(...) in JavaFX. In a SwingWorker, call publish and update the label in process, which runs on the event dispatch thread.
Why does process receive a list?
Swing may combine several publish calls into one process call, especially when the background thread publishes faster than the UI can handle. Often only the last element matters, for example the current line number.
Can I run the same SwingWorker twice?
No. Each worker object runs once. Create a new worker for every job.
Should I use invokeAndWait?
Rarely. It blocks the calling thread until the UI code has run, and calling it from the event dispatch thread itself throws an Error. invokeLater is almost always the better choice.
API reference
javax.swing.SwingWorker<T, V>
| Method | Description |
|---|---|
protected abstract T doInBackground() | override to do the work on a worker thread and return the result |
protected void process(List<V> data) | override to handle published progress data on the EDT |
protected final void publish(V... data) | sends progress data to process; call from doInBackground |
protected void done() | override to finish up on the EDT after completion or cancellation |
void execute() | schedules the worker on a worker thread (only once per object) |
T get(), boolean cancel(boolean mayInterrupt), boolean isCancelled(), boolean isDone() | Future methods |
SwingWorker.StateValue getState() | PENDING, STARTED or DONE |
protected final void setProgress(int p), int getProgress() | bound property 0–100, observed via addPropertyChangeListener |
java.awt.EventQueue
| Method | Description |
|---|---|
static void invokeLater(Runnable r) | runs r on the EDT after pending events |
static void invokeAndWait(Runnable r) | runs r on the EDT and waits; never call from the EDT |
static boolean isDispatchThread() | true if the current thread is the EDT |
Summary
- UI toolkits use a single UI thread and non-thread-safe components. Never block that thread, and never touch components from any other thread.
- Run slow work in background threads and send UI updates back with
EventQueue.invokeLater(Swing),Platform.runLater(JavaFX) or the main-thread handler (Android). SwingWorker<T, V>structures the job.doInBackgroundruns in the background andpublishes progress,processreceives batched progress on the EDT, anddonefinishes on the EDT, callingget()for the result or detecting cancellation.- Workers are single-use.
cancel(true)interrupts the worker, so react to interrupts or checkisCancelled(). - JavaFX
Taskand Android coroutines orWorkManagerfollow the same model.
Practice Questions
Why does a Swing program freeze when a button handler reads a large file directly?
The handler runs on the event dispatch thread. While it reads, that thread can't process other events or repaint, so the whole window stops responding until the handler returns.
A background thread calls label.setText(...). What is wrong, and how do you fix it?
Swing components aren't thread-safe and may only be accessed from the EDT. Calling them from another thread can corrupt their state, and JavaFX and Android would throw. Wrap the call in EventQueue.invokeLater(() -> label.setText(...)).
Why does process receive a List rather than a single value?
Swing may combine several publish calls into a single process call on the EDT to reduce overhead. The list contains all values published since the last call, in order.
Where should you call get() on a SwingWorker, and why not right after execute()?
Call it in done(), which runs on the EDT after the work has finished, so get() returns immediately. Calling it right after execute() on the EDT would block the UI thread until the work completes, which defeats the purpose.
Can you call execute() twice on the same SwingWorker to load a second file?
No. A SwingWorker is designed to run only once, and a second execute() has no effect. Create a new worker object for each job.
Previous: Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
Next: Java Processes and ProcessBuilder: Running and Managing External Programs
Related reading
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
- Java Primitive Types: Integers and Floating-Point Numbers Explained
- Java Collectors.toMap: Collecting Streams into Maps

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.