> Markdown version of [Server Push](https://vaadin.com/docs/latest/flow/advanced/server-push). Section index: [llms.txt](https://vaadin.com/docs/latest/flow/llms.txt)

# <a id="push.configuration"></a>Server Push

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](https://github.com/Atmosphere/atmosphere) internally for server push communication.

For practical usage guides and patterns, see [Server Push](https://vaadin.com/docs/latest/building-apps/server-push.md) in the Building Apps section.

## <a id="push.configuration.annotation"></a>The @Push Annotation

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

```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](#push.configuration.pushmode).                   |
| `transport` | `Transport.WEBSOCKET_XHR` | The transport mechanism. See [Transport Options](#push.configuration.transport). |

## <a id="push.configuration.pushmode"></a>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:

```java
@Push(PushMode.MANUAL)
public class Application implements AppShellConfigurator {
  ...
}
```

## <a id="push.configuration.transport"></a>Transport Options

<!-- vale Vaadin.Abbr = NO -->

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)](#push.configuration.transport.sse). |

<!-- vale Vaadin.Abbr = YES -->

Example with long polling:

```java
@Push(transport = Transport.LONG_POLLING)
public class Application implements AppShellConfigurator {
  ...
}
```

### <a id="push.configuration.transport.sse"></a>Server-Sent Events (Experimental) (new in V25.3)

`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](https://vaadin.com/docs/latest/flow/configuration/feature-flags.md). Selecting it while the feature flag is disabled throws a `DisabledFeatureException`.

```java
@Push(transport = Transport.SERVER_SENT_EVENTS)
public class Application implements AppShellConfigurator {
  ...
}
```

## <a id="push.configuration.servlet"></a>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.

## <a id="push.access"></a>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](https://vaadin.com/docs/latest/flow/ui-state.md) is the exception. Another thread can change the signal without locking the session, and the component updates itself, as described in [Thread Safety](https://vaadin.com/docs/latest/flow/ui-state/local-signals.md#thread-safety).

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

```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:

```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.

For detailed patterns and best practices for using `UI.access()`, including how to avoid memory leaks and flooding, see [Pushing UI Updates](https://vaadin.com/docs/latest/building-apps/server-push/updates.md).

### <a id="push.access.ui"></a>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:

```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.

### <a id="push.access.order"></a>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:

```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()`:

```java
if (ui.getSession().hasLock()) {
    statusLabel.setText(statusText);
} else {
    ui.access(() -> statusLabel.setText(statusText));
}
```

### <a id="push.access.later"></a>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:

```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.

### <a id="push.access.undelivered"></a>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()` (new in V25.3) against the current time before calling `access()`. The method can be called without holding the session lock. See [Undelivered Invocations](https://vaadin.com/docs/latest/flow/component-internals/element-api/calling-javascript.md#undelivered-invocations) for an example, and for the warning that Flow logs when JavaScript invocations pile up.

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