Docs

Server Push

Configuring server push, and updating the UI from other threads in Vaadin Flow applications.

Server push is based on a client-server connection established by the client. The server can then use the connection to send updates to the client. Vaadin uses the Atmosphere framework internally for server push communication.

The @Push Annotation

Enable server push by adding the @Push annotation to the class implementing AppShellConfigurator:

Source code
Java
@Push
public class Application implements AppShellConfigurator {
  ...
}

The annotation supports the following parameters:

Parameter Default Description

value

PushMode.AUTOMATIC

The push mode. See Push Modes.

transport

Transport.WEBSOCKET_XHR

The transport mechanism. See Transport Options.

Push Modes

Server push operates in one of three modes:

Mode Description

PushMode.AUTOMATIC

Changes are pushed to the browser automatically after UI.access() finishes. This is the default mode.

PushMode.MANUAL

Changes are pushed only when you explicitly call UI.push(). Use this for fine-grained control over when updates are sent.

PushMode.DISABLED

Server push is disabled. Use this to explicitly disable push when needed.

Example with manual mode:

Source code
Java
@Push(PushMode.MANUAL)
public class Application implements AppShellConfigurator {
  ...
}

Transport Options

Server push supports the following transport mechanisms:

Transport Description

Transport.WEBSOCKET_XHR

Combined WebSockets and XHR. WebSocket is used for server-to-client communication, and XHR for client-to-server communication. This is the default and recommended transport.

Transport.WEBSOCKET

Pure WebSocket connection.

Transport.LONG_POLLING

HTTP long polling. Use this if WebSocket connections are blocked by proxies or firewalls.

Transport.SERVER_SENT_EVENTS

Server-sent events for server-to-client communication, and XHR for client-to-server communication. Experimental; see Server-Sent Events (Experimental).

Example with long polling:

Source code
Java
@Push(transport = Transport.LONG_POLLING)
public class Application implements AppShellConfigurator {
  ...
}

Server-Sent Events (Experimental)

Transport.SERVER_SENT_EVENTS streams server-to-client messages using the browser’s EventSource API, while client-to-server messages are sent as regular XHR requests. It can help when running behind proxies or firewalls that allow plain HTTP streaming but block WebSocket connections.

This transport is experimental and requires enabling the ssePushTransport feature flag; see Feature Flags. Selecting it while the feature flag is disabled throws a DisabledFeatureException.

Source code
Java
@Push(transport = Transport.SERVER_SENT_EVENTS)
public class Application implements AppShellConfigurator {
  ...
}

Servlet Configuration

If you’re manually configuring your servlet, set the async-supported parameter to enable push support.

You can also configure push mode for the entire application in the servlet configuration with the pushMode parameter in the web.xml deployment descriptor, or a corresponding @WebServlet annotation.

On the server side, the push endpoint is mapped to the VAADIN/push path. This mapping is added either under context root, context path, or the first URL mapping (sorted by natural order and ignoring /VAADIN/* and /vaadinServlet/*) of the Vaadin servlet, depending on application deployment configuration. For multiple servlet mappings, configure the pushServletMapping parameter to match the desired mapping.

Updating the UI from Another Thread

Flow locks the user session while it handles a request, for example while it runs an event listener. Code that runs in another thread has to lock the session as well before it reads or changes the components of a UI. Otherwise, its changes can conflict with those of a request.

A component bound to a signal is the exception. Another thread can change the signal without locking the session, and the component updates itself, as described in Thread Safety.

For other changes, the UI.access() method runs a task with the session locked:

Source code
Java
ui.access(() -> statusLabel.setText(statusText));

While the task runs, UI.getCurrent(), VaadinSession.getCurrent() and VaadinService.getCurrent() return that UI, its session and its service. VaadinService.getCurrentRequest() and VaadinService.getCurrentResponse() return null.

With automatic push, the changes are pushed to the browser when the session lock is released after the task. With manual push, call UI.push() in the task:

Source code
Java
ui.access(() -> {
    statusLabel.setText(statusText);
    ui.push();
});

If the UI has been detached, for example because its session has expired, access() throws a UIDetachedException. A queued task whose UI is detached before the task runs doesn’t run.

Getting the UI Instance

Call access() on the UI instance whose components the task changes. Get the instance while the session is locked, and pass it to the other thread. The other thread can’t get it in the usual ways:

  • UI.getCurrent() returns the UI that Flow has set for the current thread. Flow sets it in the thread that handles a request for the UI, and while a task passed to access() runs. A background thread has no current UI: UI.getCurrent() returns null there, and UI.getCurrentOrThrow() throws an IllegalStateException.

  • Component.getUI() reads the component tree. Like other component methods, it’s only safe to call while holding the session lock.

In the following example, the click listener gets the UI instance in the request thread, before it starts the background work:

Source code
Java
button.addClickListener(event -> {
    UI ui = UI.getCurrentOrThrow(); 1
    executor.execute(() -> {
        String status = reportService.generateReport(); 2
        ui.access(() -> statusLabel.setText(status));
    });
});
  1. The listener runs in the request thread, which holds the session lock.

  2. The background thread uses the instance that the listener got.

In onAttach(), the AttachEvent gives the UI instance through its getUI() method.

When the Task Runs

The access() method adds the task to a queue of the session. The tasks in the queue run in the order they were added, with the session locked. When they run depends on which thread holds the session lock:

Session Lock When the Task Runs

Not held by any thread

access() acquires the lock and runs the task in the calling thread, before it returns.

Held by another thread

access() returns right away. The task runs in the thread that holds the lock, before that thread releases it.

Held by the calling thread, for example in an event listener

access() returns right away. The task runs later in the same thread, before the thread releases the lock. In a request, it runs after the event listeners have returned, before the response is written.

As the task can run in a thread other than the one that called access(), it can’t rely on the thread-local values of the calling thread.

The changes that a request thread makes after calling access() are applied before the changes of the task. In the following example, the listener adds its Div first, although it calls access() before that:

Source code
Java
Button button = new Button("Add", event -> {
    UI.getCurrentOrThrow().access(() -> add(new Div("Added by the task")));
    add(new Div("Added by the listener"));
});

After a click, the view shows "Added by the listener" above "Added by the task".

A thread that holds the session lock can change the UI directly, without access(). Code that runs both in request threads and in other threads can check whether the current thread holds the lock with VaadinSession.hasLock():

Source code
Java
if (ui.getSession().hasLock()) {
    statusLabel.setText(statusText);
} else {
    ui.access(() -> statusLabel.setText(statusText));
}

Callbacks That Update the UI

The UI.accessLater() method wraps a task in a callback that runs the task through access() on that UI. Pass the callback to code that calls it from another thread without locking the session, such as a CompletableFuture or an event bus:

Source code
Java
button.addClickListener(event -> {
    UI ui = UI.getCurrentOrThrow();
    reportService.generateReportAsync().thenAccept(ui.accessLater(
            report -> showReport(report),
            null)); // No detach handler
});

The method has two variants:

Method Returns

accessLater(SerializableRunnable accessTask, SerializableRunnable detachHandler)

A SerializableRunnable that runs accessTask through access().

accessLater(SerializableConsumer<T> accessTask, SerializableRunnable detachHandler)

A SerializableConsumer<T> that runs accessTask through access(), and passes it the value that the consumer receives.

The accessTask argument is the task that changes the UI. It can’t be null.

The detachHandler argument is a handler that runs instead of the task when the UI has been detached. That applies both when the UI is detached by the time the callback is called, and when it’s detached by the time the queued task would run. With null, a detached UI is handled as with access(): the callback throws a UIDetachedException, or the queued task doesn’t run.

Undelivered Updates

The changes to a UI and its JavaScript invocations are held in memory on the server until a response is written for the browser. That takes an open push connection, or a request from the UI in the browser, for example after a user interaction. Heartbeat requests don’t carry updates. Until then, the updates that a background task makes pile up. This happens, for example, when a laptop has gone to sleep, the push connection has closed, or the browser has discarded the tab. For a browser that doesn’t come back, the updates pile up until the UI is detached, at the latest when the session expires.

To stop updating a UI whose browser isn’t receiving the updates, compare UI.getLastUpdateSentTimestamp() against the current time before calling access(). The method can be called without holding the session lock. See Undelivered Invocations for an example, and for the warning that Flow logs when JavaScript invocations pile up.

77E22B23-4E6A-4D32-AFCC-2423F633F81D

Updated –