Vaadin Push for Server Updates From Background Threads
Use Vaadin Push to update the UI from background threads: enable Push on the app shell, wrap changes in ui.access, and handle detach and long running tasks.

A Vaadin view normally changes only in response to a user action: a click arrives, the server updates components, and the response carries the changes back. Server push breaks that rule. It lets the server send changes at any moment, for a progress bar, a live feed or a notification caused by another user. The mechanism is simple to switch on and has one rule that must be followed every time, which is to touch components only while the session is locked. This post covers both on Vaadin 25 with Spring Boot 4 and JDK 25.
Turn it on
Annotate the application shell, the class that implements AppShellConfigurator:
@Push
@SpringBootApplication
public class Application implements AppShellConfigurator {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}@Push opens a WebSocket between the browser and the server, falling back to long polling if the socket cannot be established, as happens behind a proxy that does not forward upgrades. @Push(PushMode.AUTOMATIC) is the default, so changes are pushed when ui.access finishes. PushMode.MANUAL pushes only when you call ui.push(), useful when you batch several changes. The transport can be set with @Push(transport = Transport.WEBSOCKET_XHR), which uses a WebSocket for messages from the server and ordinary requests for messages from the client, and is the most compatible setting for hostile proxies.
Update from another thread
The server holds a lock on the user's VaadinSession while it handles a request, so the component tree is touched by one thread at a time. A background thread that changes a component without the lock corrupts that guarantee, and Vaadin throws IllegalStateException ("Cannot access state in VaadinSession or UI without locking the session"). The way in is ui.access:
@Route("import")
class ImportView extends VerticalLayout {
private final ProgressBar bar = new ProgressBar(0, 100);
private final ImportService service;
ImportView(ImportService service) {
this.service = service;
var start = new Button("Start import", e -> start(UI.getCurrent()));
add(start, bar);
}
private void start(UI ui) {
CompletableFuture.runAsync(() ->
service.run(percent -> ui.access(() -> bar.setValue(percent))));
}
}ui.access(Command) schedules the command to run with the session locked and pushes the changes afterwards. It returns a Future and does not block the caller. Capture the UI on the request thread, as the example does, because UI.getCurrent() is null on any other thread. Capture the UI, not a component, in the background task: a component keeps its whole parent tree alive, and the UI reference is the cheap handle.
For work started by a click, service.run should be on an executor you manage, not the common pool, so you can cap concurrency and shut it down; see thread pools used properly. Do not hold the session lock during the long work. Only the short access block runs under the lock, and the slow computation runs outside it.
Handle detach
A user can close the tab while the task runs. The UI is then detached, and ui.access throws UIDetachedException when the session has expired. Check before updating, or catch it:
private void pushIfAttached(UI ui, Runnable change) {
if (ui.isAttached()) {
try {
ui.access(change::run);
} catch (UIDetachedException ignored) {
// the tab closed between the check and the call
}
}
}For long-lived subscriptions, register on attach and unregister on detach. A listener left behind keeps a reference to the dead UI in a long-lived object, and this is the leak that grows until the server runs out of memory, covered in session memory.
@Override
protected void onAttach(AttachEvent event) {
registration = broadcaster.register(message ->
event.getUI().access(() -> feed.add(new Span(message))));
}
@Override
protected void onDetach(DetachEvent event) {
if (registration != null) registration.remove();
}Broadcast to many users
For events that reach every connected user, such as "a new order arrived", keep one application-scoped publisher and let each view subscribe:
@Component
class Broadcaster {
private final Set<Consumer<String>> listeners = ConcurrentHashMap.newKeySet();
Registration register(Consumer<String> listener) {
listeners.add(listener);
return () -> listeners.remove(listener);
}
void publish(String message) {
listeners.forEach(l -> l.accept(message));
}
}Each listener calls ui.access itself, so one slow client does not block the others, and exceptions in one access do not stop the loop. For many thousands of connected clients, publish to a queue and let a bounded executor deliver. Across several server nodes, the in-memory set reaches only the users on one node, so forward events through a message broker.
Polling instead
ui.setPollInterval(2000) makes the browser ask the server every two seconds. It needs no WebSocket, passes through any proxy and costs a request per poll per user. Use it when push is blocked or when updates are rare and tolerant of delay. A grid refreshed every ten seconds does not need a persistent connection. Turn polling off with setPollInterval(-1) when the task finishes.
Thread safety
Objects shared between threads are your responsibility. The lock protects the UI, not your beans. A service updated from several sessions needs its own synchronisation or concurrent collections. Do not call ui.access while holding a lock that the UI thread also needs, or you can deadlock.
Testing push code
Code that calls ui.access is hard to test with a real browser, so test the logic around it. Keep the work in a service that reports progress through a callback, and test the service with a plain callback that records values. For the view, a Vaadin TestBench or browser-less UI unit test can assert that the progress bar's value changes when the callback fires. The part that needs a real browser is the transport, and it is worth a single end-to-end check in staging with the proxy that production uses, because WebSocket support differs from proxy to proxy.
Look at the connection in the browser's network tab: a request with status 101 and the type websocket shows push working, and repeated long requests show the fallback. If you see the fallback in production but not locally, the load balancer is stripping the upgrade header or timing out idle connections. Raise its idle timeout above Vaadin's heartbeat interval so the socket is not closed between pushes.
Session expiry and push
Push messages count as server activity for the websocket, but not for the session timeout, which counts requests. A user who leaves a dashboard open and receives pushes for an hour can still have the session expire, because the browser sent no request. Heartbeats, sent by Vaadin every few minutes, keep the UI alive but are configured to not extend the HTTP session unless closeIdleSessions is false. Decide which behaviour you want for dashboards that stay open, and set vaadin.closeIdleSessions accordingly. A dashboard that logs the user out in the middle of a live feed is a support ticket waiting to happen.
Where push does not belong
Each push connection holds a socket and some memory on the server for as long as the tab is open, so 20,000 idle users cost 20,000 connections. If your updates matter to a handful of screens, push only on those routes with @Push on a layout instead of the whole shell. For a read-heavy public site, push is the wrong tool. The production considerations are in the production build, and lazy data in lazy grids. The API is in the UI Javadoc, and the feature in the server push documentation.


