Skip to content

Feat/UI locking - #26804

Open
OriginalFelix wants to merge 10 commits into
vaadin:mainfrom
OriginalFelix:feat/ui-locking
Open

OriginalFelix wants to merge 10 commits into
vaadin:mainfrom
OriginalFelix:feat/ui-locking

Conversation

@OriginalFelix

Copy link
Copy Markdown

Description

This PR adds UI-Locking behind a Feature-Flag. Reason is that always taking the Lock even when a Component is Updated blocks every UI from Working so Updates can be slow when there are many of them.

This PR separates UI Relevant Updates from Session-Updates and adds a new Lock. (Only if the Feature-Flag is enabled)

Fixes #24187

This PR adds UI-Locking behind a Feature-Flag. Old behavior remains untouched without the flag.

  • Bugfix
  • Feature

Checklist

  • I have read the contribution guide: https://vaadin.com/docs/latest/guide/contributing/overview/
  • I have added a description following the guideline.
  • The issue is created in the corresponding repository and I have referenced it.
  • I have added tests to ensure my change is effective and works as intended.
  • New and existing tests are passing locally with my change.
  • I have performed self-review and corrected misspellings.

Additional for Feature type of change

  • Enhancement / new feature was discussed in a corresponding GitHub issue and Acceptance Criteria were created.

OriginalFelix and others added 8 commits October 28, 2026 13:07
Moves the UI bookkeeping out of VaadinSession into a new
SessionUIService owned by VaadinService. It holds a
ConcurrentHashMap<VaadinSession, CopyOnWriteArrayList<UI>>, so UIs can
be enumerated lock-free. VaadinSession keeps its public API and
delegates to the service.

- Session destroy removes the session entry to avoid leaks.
- Serialization keeps the Map<Integer, UI> stream format; UIs are held
  locally after deserialization and moved to the service in
  refreshTransients.
- Falls back to a session local store when the service provides none
  (e.g. mocked services).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TKXmkBLF5XfNVJ3CFAYj7v
With the uiLocking init parameter, updating a UI locks only that UI, so
UIs of one session (browser tabs) are updated in parallel.

- UIDL, heartbeat and push messages lock the UI, not the session.
- UI.access() uses a queue per UI, pushed when the UI lock is released.
- Session state (attributes, registries, ids) is thread-safe and
  accessible while holding a UI lock.
- Lock order: a UI lock holder may wait for the session lock; a session
  lock holder never waits for a UI lock (tryLock or UI.access()).
- Spring and CDI session scopes lock the session for shared bookkeeping.

Disabled by default; session locking is unchanged.
@mshabarov mshabarov added the Contribution PRs coming from the community or external to the team label Nov 2, 2026
# Conflicts:
#	flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java
#	flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java
#	flow-server/src/main/java/com/vaadin/flow/server/communication/PushHandler.java
#	flow-server/src/main/java/com/vaadin/flow/server/communication/StreamReceiverHandler.java
#	flow-server/src/main/java/com/vaadin/flow/server/communication/StreamRequestHandler.java
#	flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java
Make SessionUIService serializable, as required for all Flow classes,
and read the session state with the lock held in the session destroy test.
@totally-not-ai

totally-not-ai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Thanks a lot for working on this! We went through the PR in detail against the design discussed in #24187. Below is a summary of what we found, followed by a proposal for how to get this in.

What the PR gets right

  • Opt-in through the init parameter uiLocking, off by default.
  • UI.access() uses a queue per UI. UIDL, heartbeat and push requests take only the UI lock, and each UI pushes when its own lock is released.
  • The lock order "a UI-lock holder may take the session lock, a session-lock holder never waits for a UI lock" is applied in the session cleanup and destroy paths (accessUIWithoutWaiting).
  • It updates the Spring and CDI scopes, upload/stream handlers and signal transactions.

Problems

  1. Session state is not protected, which the design explicitly ruled out. VaadinSession.hasAccess() returns true when the thread holds any UI lock of the session, and checkHasLock() now goes through it. Session attributes and other session state can be changed from several UI threads at once without any check failing. The PR makes individual fields thread-safe (Attributes → ConcurrentHashMap, volatile, copy-on-write lists), but app code that reads and then writes, like if (getAttribute(x) == null) setAttribute(x, …), now races silently. This is exactly the case the discussion in Locking issue when using Multiple Tabs in a near Real-Time-Application #24187 warned against. The PR also does not leave VaadinSession.getCurrent() unset during UI handling as the design specified.
  2. New cross-session deadlock. verifyNoOtherSessionLocked only checks otherSession.hasLock(). Holding a UI lock does not count, so the check passes. Thread A holds the lock of UI X1 (session X) and calls accessSynchronously on UI Y1 (session Y). For session Y, hasAccess() is false, so A waits on lockUI(). Thread B does the reverse and both wait forever. This is the usual broadcaster pattern: in a click handler, push to other users' UIs. Today it fails right away with an exception; with this PR it deadlocks.
  3. A rule that fails only under load. The design says waiting on a UI lock while holding the session lock always throws. The PR uses tryLock() and throws only if the UI is busy at that moment (UI.accessSynchronouslyWithUILock). Code passes tests and then fails under real concurrency. The same applies when a thread holding UI1 calls accessSynchronously on UI2.
  4. "Old behavior remains untouched without the flag" is not true.
    • UIs now live in a SessionUIService owned by VaadinService, a map keyed by session for the whole service, even with the flag off. Before, UIs lived inside the session and were collected with it. Now they are removed only in fireSessionDestroy. Any path that drops a session without that event leaks the session and all its UI trees: passivation or replication, sessions cleared without unbinding, test mocks.
    • Attributes is also what ComponentUtil.setData uses on every component, so every component that stores data gets a heavier ConcurrentHashMap.
    • The serialized form of VaadinSession changes: nextUIId goes from int to AtomicInteger and requestHandlers from LinkedList to CopyOnWriteArrayList. Sessions serialized by the previous version will fail to deserialize after an upgrade (session persistence, Kubernetes Kit rolling updates).
    • The design only asked for uIs to become a ConcurrentHashMap inside the session, which avoids all of this.
  5. Smaller items:
    • Spring and CDI lock the session through getLockInstance().lock(), which bypasses VaadinSession.unlock(). Tasks queued with VaadinSession.access while that lock is held won't run until some later unlock.
    • On session destroy, a busy UI's close() is deferred with ui.access() and may run after the session is already CLOSED and removed.
    • UILockingTest is in package server while UIInternals lock methods are public "framework internal" API. That's a lot of new public surface: lockForUI, getUIsWithoutLock, findUIWithoutLock, SessionUIService, canHandleWithUILock.
    • The description calls it a "Feature-Flag", but it is an init parameter.
    • The forEachUi helper from the design is missing.

Proposed way forward

Because the change touches the core threading model, we'd like to land it in smaller, reviewable steps rather than as one PR. We've split #24187 into sub-issues (linked from the issue):

  1. Agree on the locking rules in Locking issue when using Multiple Tabs in a near Real-Time-Application #24187 first:
    • Lock order: a thread holding a UI lock may take the session lock. A thread holding a session lock may never wait for a UI lock.
    • Deterministic failures: accessSynchronously / lock() on a UI while holding the session lock throws IllegalStateException every time, not only when the UI happens to be busy (no tryLock() heuristics). The same applies to holding a UI lock of another session, so verifyNoOtherSessionLocked must also treat UI locks as held.
    • Session state: holding a UI lock does not give access to session state. VaadinSession.checkHasLock() keeps requiring the session lock, and app code locks the session explicitly for attributes.
    • Whether VaadinSession.getCurrent() is set during UI-locked handling.
  2. UI lock API that delegates to the session lock (refactor only). (UI locking: add UI lock API that delegates to the session lock #27580)
  3. Make the framework's own session internals thread-safe (no behaviour change, serialization compatible). (UI locking: make VaadinSession internals thread-safe #27581)
  4. UI locking core behind an experimental feature flag. (UI locking: per-UI lock core behind an experimental feature flag #27582)
  5. Push and stream handling. (UI locking: push and stream handling #27583)
  6. Integrations (Spring, CDI, signals, setLocale). (UI locking: Spring, CDI, signals and setLocale integrations #27584)
  7. Finishing: forEachUi, documentation, promote the flag to a configuration property. (UI locking: forEachUi helper, documentation and configuration property #27585)

Much of the code in this PR can be reused in those steps. Steps 1–2 are safe refactors that can merge quickly and make step 3, the actual concurrency change, much smaller to review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Contribution PRs coming from the community or external to the team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Locking issue when using Multiple Tabs in a near Real-Time-Application

2 participants