Docs

Documentation versions (currently viewingVaadin 24)

Server Push Configuration

Server push allows you to update the UI from the server for the users without them requesting updates.
Important
This page is being migrated to the new Building Applications section. See the Background Jobs and Server Push documentation pages.

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. For example, it could send a new chat message to all participants without delay.

The server-client communication uses a WebSocket connection, if supported by the browser and the server. If not, the connection resorts to whatever method is supported by the browser. Vaadin uses the Atmosphere framework, internally.

Enabling Push in Your Application

To enable server push, you’ll need to define the push mode either in the deployment descriptor, or with the @Push annotation on your application shell class.

The application shell class is a plain Java class implementing the AppShellConfigurator interface. The class is detected and instantiated by Vaadin during bootstrap. Only one application shell class is allowed. An exception is thrown if more than one class implements AppShellConfigurator.

For example, you can use the following Application class — which implements the AppShellConfigurator interface — to enable server push in your application by adding the @Push annotation to it.

@Push
public class Application implements AppShellConfigurator {
  ...
}

Push Modes & Transports

You can use server push in two modes: automatic and manual. The automatic mode automatically pushes changes to the browser after access() finishes. With the manual mode, you can do the push explicitly with push(), which allows more flexibility.

Server push can use several transports: WebSockets, long polling, or combined WebSockets+XHR. WebSockets+XHR is the default transport.

The @Push Annotation

You can enable server push for the application annotating the application shell class with the @Push annotation as in the example here. It defaults to automatic mode (i.e., PushMode.AUTOMATIC).

@Push
public class Application implements AppShellConfigurator {
  ...
}

To enable manual mode, you need to pass the PushMode.MANUAL parameter, as follows:

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

To use the long polling transport, you’ll need to set the transport parameter to Transport.LONG_POLLING, as follows:

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

Servlet Configuration

If you’re manually configuring your servlet, be sure to set the async-supported parameter.

You can enable server push and define the push mode for an entire application in the servlet configuration with the pushMode parameter for the servlet 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. In case of multiple servlet mappings, it’s possible to set the URL mapping for server push by configuring the pushServletMapping parameter to match the desired mapping.

Asynchronous Updates

Making changes to a UI from another thread and pushing them to the browser requires locking the user session. Otherwise, the UI update done from another thread could conflict with a regular event-driven update and cause either data corruption or deadlocks. Because of this, you may only access a UI using the access() method, which locks the session to prevent conflicts. It takes as a parameter a Command to execute while the session is locked.

Below is an example of this:

ui.access(new Command() {
    @Override
    public void execute() {
        statusLabel.setText(statusText);
    }
});

You can also use a lambda expression to define your access command, like so:

ui.access(() -> statusLabel.setText(statusText));

If the push mode is manual, you need to push the pending UI changes to the browser explicitly with the push() method.

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

The following is a complete example showing how to make UI changes from another thread:

@Route("push")
public class PushyView extends VerticalLayout {
    private FeederThread thread;

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        add(new Span("Waiting for updates"));

        // Start the data feed thread
        thread = new FeederThread(attachEvent.getUI(), this);
        thread.start();
    }

    @Override
    protected void onDetach(DetachEvent detachEvent) {
        // Cleanup
        thread.interrupt();
        thread = null;
    }

    private static class FeederThread extends Thread {
        private final UI ui;
        private final PushyView view;

        private int count = 0;

        public FeederThread(UI ui, PushyView view) {
            this.ui = ui;
            this.view = view;
        }

        @Override
        public void run() {
            try {
                // Update the data for a while
                while (count < 10) {
                    // Sleep to emulate background work
                    Thread.sleep(500);
                    String message = "This is update " + count++;

                    ui.access(() -> view.add(new Span(message)));
                }

                // Inform that we're done
                ui.access(() -> {
                    view.add(new Span("Done updating"));
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

When sharing data between UIs or user sessions, you need to consider the message-passing mechanism, as explained in the next section.

Collaborative Views

Broadcasting messages, to be pushed to UIs in other user sessions, requires some sort of message-passing mechanism that sends the messages to all UIs that are registered as recipients. Since processing server requests for different UIs happens concurrently in different threads of the application server, locking the data structures is important to avoid deadlock situations.

The Broadcaster

The standard pattern for sending messages to other users is to use a broadcaster singleton that registers recipients and broadcasts messages to them. To avoid deadlocks, it’s recommended that the messages are sent through a message queue in a separate thread. Using a Java ExecutorService running a single thread is one of the easiest and safest ways. The methods in the class are defined as synchronized to prevent race conditions.

public class Broadcaster {
    static Executor executor = Executors.newSingleThreadExecutor();

    static LinkedList<Consumer<String>> listeners = new LinkedList<>();

    public static synchronized Registration register(
            Consumer<String> listener) {
        listeners.add(listener);

        return () -> {
            synchronized (Broadcaster.class) {
                listeners.remove(listener);
            }
        };
    }

    public static synchronized void broadcast(String message) {
        for (Consumer<String> listener : listeners) {
            executor.execute(() -> listener.accept(message));
        }
    }
}

Receiving Broadcasts

The receivers need to register a consumer to the broadcaster to receive the broadcasts. The registration should be removed when the component is no longer attached. When updating the UI in a receiver, you should do this safely by executing the update through the access() method of the UI, as described in the previous section (see Asynchronous Updates).

@Route("broadcaster")
public class BroadcasterView extends Div {
    VerticalLayout messages = new VerticalLayout();
    Registration broadcasterRegistration;

    // Creating the UI shown separately

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        UI ui = attachEvent.getUI();
        broadcasterRegistration = Broadcaster.register(newMessage -> {
            ui.access(() -> messages.add(new Span(newMessage)));
        });
    }

    @Override
    protected void onDetach(DetachEvent detachEvent) {
        broadcasterRegistration.remove();
        broadcasterRegistration = null;
    }
}

Sending Broadcasts

To send broadcasts with a broadcaster singleton, such as the one described previously, you would only need to call the broadcast() method, as follows:

@Route("broadcaster")
public BroadcasterView() {
    TextField message = new TextField();
    Button send = new Button("Send", e -> {
        Broadcaster.broadcast(message.getValue());
        message.setValue("");
    });

    HorizontalLayout sendBar = new HorizontalLayout(message, send);

    add(sendBar, messages);
}

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