From 3c5781b54140328919df39e48a977e9e1eac023e Mon Sep 17 00:00:00 2001 From: OriginalFelix Date: Wed, 28 Oct 2026 13:07:22 +0100 Subject: [PATCH 1/8] feat: store session UIs in a SessionUIService Moves the UI bookkeeping out of VaadinSession into a new SessionUIService owned by VaadinService. It holds a ConcurrentHashMap>, 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 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 Claude-Session: https://claude.ai/code/session_01TKXmkBLF5XfNVJ3CFAYj7v --- .../vaadin/flow/server/SessionUIService.java | 152 ++++++++++++++++++ .../com/vaadin/flow/server/VaadinService.java | 28 ++++ .../com/vaadin/flow/server/VaadinSession.java | 57 ++++++- .../flow/server/SessionUIServiceTest.java | 128 +++++++++++++++ .../vaadin/flow/server/VaadinSessionTest.java | 23 +++ 5 files changed, 381 insertions(+), 7 deletions(-) create mode 100644 flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java create mode 100644 flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java diff --git a/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java b/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java new file mode 100644 index 00000000000..d8b727025d4 --- /dev/null +++ b/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java @@ -0,0 +1,152 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.server; + +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; + +import com.vaadin.flow.component.UI; + +/** + * Keeps track of the {@link UI} instances of every {@link VaadinSession} + * outside of the session itself. + *

+ * The storage is a {@link ConcurrentHashMap} keyed by the session (identity, + * since {@link VaadinSession} does not override {@code equals}) with a + * {@link CopyOnWriteArrayList} of UIs as value. Reads are therefore lock-free + * and iteration always works on a consistent snapshot, which makes it possible + * to enumerate UIs without holding the session lock (e.g. for broadcasting or + * monitoring). Mutating a UI still requires its session lock as usual. + *

+ * Writes are expected to happen through {@link VaadinSession#addUI(UI)} and + * {@link VaadinSession#removeUI(UI)}, i.e. while the session lock is held. + *

+ * One instance is owned by each {@link VaadinService}, see + * {@link VaadinService#getSessionUIService()}. + * + * @since 25.4 + */ +public class SessionUIService { + + private final ConcurrentHashMap> uisBySession = new ConcurrentHashMap<>(); + + /** + * Gets the UIs of the given session. + * + * @param session + * the session, not {@code null} + * @return an unmodifiable, thread-safe view of the session's UIs, never + * {@code null} + */ + public List getUIs(VaadinSession session) { + Objects.requireNonNull(session, "Session cannot be null"); + CopyOnWriteArrayList uis = uisBySession.get(session); + return uis == null ? Collections.emptyList() + : Collections.unmodifiableList(uis); + } + + /** + * Gets the UI with the given id from the given session. + * + * @param session + * the session, not {@code null} + * @param uiId + * the UI id + * @return the UI, or {@code null} if not found + */ + public UI getUIById(VaadinSession session, int uiId) { + for (UI ui : getUIs(session)) { + if (ui.getUIId() == uiId) { + return ui; + } + } + return null; + } + + /** + * Registers a UI for the given session. An already registered UI with the + * same id is replaced. + * + * @param session + * the session, not {@code null} + * @param ui + * the UI, not {@code null} + */ + public void addUI(VaadinSession session, UI ui) { + Objects.requireNonNull(session, "Session cannot be null"); + Objects.requireNonNull(ui, "UI cannot be null"); + uisBySession.compute(session, (key, uis) -> { + CopyOnWriteArrayList list = uis == null + ? new CopyOnWriteArrayList<>() + : uis; + list.removeIf(existing -> existing.getUIId() == ui.getUIId()); + list.add(ui); + return list; + }); + } + + /** + * Removes a UI from the given session. + * + * @param session + * the session, not {@code null} + * @param ui + * the UI, not {@code null} + * @return {@code true} if the UI was registered + */ + public boolean removeUI(VaadinSession session, UI ui) { + Objects.requireNonNull(session, "Session cannot be null"); + Objects.requireNonNull(ui, "UI cannot be null"); + CopyOnWriteArrayList uis = uisBySession.get(session); + return uis != null + && uis.removeIf(existing -> existing.getUIId() == ui.getUIId()); + } + + /** + * Drops all bookkeeping for the given session. Must be called when the + * session is destroyed, otherwise the session and its UIs leak. + * + * @param session + * the session, not {@code null} + * @return the UIs that were still registered, never {@code null} + */ + public List removeSession(VaadinSession session) { + Objects.requireNonNull(session, "Session cannot be null"); + CopyOnWriteArrayList uis = uisBySession.remove(session); + return uis == null ? Collections.emptyList() + : Collections.unmodifiableList(uis); + } + + /** + * Gets all sessions that currently have registered UIs. + * + * @return an unmodifiable, weakly consistent view of the sessions + */ + public Set getSessions() { + return Collections.unmodifiableSet(uisBySession.keySet()); + } + + /** + * Removes all registered sessions and UIs. + */ + public void clear() { + uisBySession.clear(); + } +} diff --git a/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java b/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java index 87f19148e70..daefc3b683f 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java @@ -172,6 +172,12 @@ public abstract class VaadinService implements Serializable { private final VaadinServiceEventBus eventBus = new VaadinServiceEventBus( this); + /* + * Lazily (re)created, so that it is also available after the service has + * been deserialized. UIs are serialized as part of their session. + */ + private transient volatile SessionUIService sessionUIService; + private SystemMessagesProvider systemMessagesProvider = DefaultSystemMessagesProvider .get(); @@ -990,6 +996,27 @@ public VaadinServiceEventBus getEventBus() { return eventBus; } + /** + * Gets the service that stores the UIs of all sessions belonging to this + * service. + * + * @return the session UI service, not {@code null} + * @since 25.4 + */ + public SessionUIService getSessionUIService() { + SessionUIService result = sessionUIService; + if (result == null) { + synchronized (this) { + result = sessionUIService; + if (result == null) { + result = new SessionUIService(); + sessionUIService = result; + } + } + } + return result; + } + /** * Adds a listener that gets notified when a new UI has been initialized. * @@ -1182,6 +1209,7 @@ public void fireSessionDestroy(VaadinSession vaadinSession) { eventBus.fireEvent(event, sessionErrorHandler(session)); session.setState(VaadinSessionState.CLOSED); + getSessionUIService().removeSession(session); }); } diff --git a/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java b/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java index 7f3a754029f..9f02585059d 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java @@ -102,7 +102,13 @@ public class VaadinSession implements HttpSessionBindingListener, Serializable { private LinkedList requestHandlers = new LinkedList<>(); private int nextUIId = 0; - private transient Map uIs = new HashMap<>(); + + /* + * Holds the UIs while no SessionUIService of a VaadinService is reachable, + * i.e. after deserialization until refreshTransients has been called, or + * when the service does not provide one (e.g. mocks in tests). + */ + private transient SessionUIService localUIService; protected WebBrowser browser = new WebBrowser(); @@ -617,7 +623,7 @@ public static void setCurrent(VaadinSession session) { */ public Collection getUIs() { checkHasLock(); - return Collections.unmodifiableCollection(uIs.values()); + return getUIService().getUIs(this); } /** @@ -631,7 +637,7 @@ public Collection getUIs() { */ public UI getUIById(int uiId) { checkHasLock(); - return uIs.get(uiId); + return getUIService().getUIById(this, uiId); } /** @@ -712,7 +718,7 @@ public void removeUI(UI ui) { assert ui != null : "Removed UI cannot be null"; assert UI.getCurrent().getUIId() == ui.getUIId() : "UIs don't match"; ui.getInternals().setSession(null); - uIs.remove(ui.getUIId()); + getUIService().removeUI(this, ui); } /** @@ -977,7 +983,34 @@ public void addUI(UI ui) { "The UI belongs to a different session"); } - uIs.put(ui.getUIId(), ui); + getUIService().addUI(this, ui); + } + + /** + * Gets the service holding the UIs of this session. This is the + * {@link SessionUIService} of the {@link VaadinService} when available. + * Otherwise a session local fallback is used, whose UIs are moved over as + * soon as the service becomes available. + * + * @return the UI service to use, not {@code null} + */ + private SessionUIService getUIService() { + VaadinService vaadinService = getService(); + SessionUIService uiService = vaadinService == null ? null + : vaadinService.getSessionUIService(); + if (uiService == null) { + if (localUIService == null) { + localUIService = new SessionUIService(); + } + return localUIService; + } + if (localUIService != null) { + for (UI ui : localUIService.removeSession(this)) { + uiService.addUI(this, ui); + } + localUIService = null; + } + return uiService; } public VaadinService getService() { @@ -1185,7 +1218,11 @@ private void readObject(ObjectInputStream stream) requestHandlers.remove(null); destroyListeners.remove(null); - uIs = (Map) stream.readObject(); + Map uis = (Map) stream.readObject(); + // The service is not yet known, keep the UIs locally until + // refreshTransients is called + localUIService = new SessionUIService(); + uis.values().forEach(ui -> localUIService.addUI(this, ui)); resourceRegistry = (StreamResourceRegistry) stream.readObject(); pendingAccessQueue = new ConcurrentLinkedQueue<>(); localeSignal = new ValueSignal<>(locale); @@ -1216,7 +1253,11 @@ private void writeObject(java.io.ObjectOutputStream stream) stream.defaultWriteObject(); if (serializeUIs) { - stream.writeObject(uIs); + // Same stream format as before: Map + Map uis = new HashMap<>(); + getUIService().getUIs(this) + .forEach(ui -> uis.put(ui.getUIId(), ui)); + stream.writeObject(uis); stream.writeObject(resourceRegistry); } else { stream.writeObject(new HashMap<>()); @@ -1244,6 +1285,8 @@ public void refreshTransients(WrappedSession wrappedSession, session = wrappedSession; service = vaadinService; refreshLock(); + // Moves UIs restored by deserialization to the service + getUIService(); } /** diff --git a/flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java b/flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java new file mode 100644 index 00000000000..b5b34a33b4c --- /dev/null +++ b/flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java @@ -0,0 +1,128 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.server; + +import java.util.Iterator; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.vaadin.flow.component.UI; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SessionUIServiceTest { + + private final SessionUIService service = new SessionUIService(); + private final VaadinSession session = mock(VaadinSession.class); + private final VaadinSession otherSession = mock(VaadinSession.class); + + @Test + void addUI_uisAreStoredPerSession() { + UI ui0 = ui(0); + UI ui1 = ui(1); + UI other = ui(0); + + service.addUI(session, ui0); + service.addUI(session, ui1); + service.addUI(otherSession, other); + + assertEquals(List.of(ui0, ui1), service.getUIs(session)); + assertEquals(List.of(other), service.getUIs(otherSession)); + assertSame(ui1, service.getUIById(session, 1)); + assertNull(service.getUIById(session, 2)); + } + + @Test + void addUI_sameId_replacesUI() { + UI first = ui(0); + UI second = ui(0); + + service.addUI(session, first); + service.addUI(session, second); + + assertEquals(List.of(second), service.getUIs(session)); + } + + @Test + void removeUI_uiIsRemoved() { + UI ui = ui(0); + service.addUI(session, ui); + + assertTrue(service.removeUI(session, ui)); + assertFalse(service.removeUI(session, ui)); + assertTrue(service.getUIs(session).isEmpty()); + } + + @Test + void removeSession_allUIsOfSessionAreDropped() { + UI ui = ui(0); + service.addUI(session, ui); + service.addUI(otherSession, ui(0)); + + assertEquals(List.of(ui), service.removeSession(session)); + assertTrue(service.getUIs(session).isEmpty()); + assertFalse(service.getSessions().contains(session)); + assertTrue(service.getSessions().contains(otherSession)); + } + + @Test + void getUIs_unknownSession_emptyAndUnmodifiable() { + List uis = service.getUIs(session); + + assertTrue(uis.isEmpty()); + assertThrows(UnsupportedOperationException.class, + () -> uis.add(ui(0))); + } + + @Test + void getUIs_iterationIsSnapshot_concurrentModificationAllowed() { + service.addUI(session, ui(0)); + service.addUI(session, ui(1)); + + Iterator iterator = service.getUIs(session).iterator(); + service.addUI(session, ui(2)); + + int count = 0; + while (iterator.hasNext()) { + iterator.next(); + count++; + } + assertEquals(2, count); + assertEquals(3, service.getUIs(session).size()); + } + + @Test + void getSessionUIService_sameInstanceForService() { + VaadinService vaadinService = new MockVaadinServletService(); + + assertSame(vaadinService.getSessionUIService(), + vaadinService.getSessionUIService()); + } + + private static UI ui(int id) { + UI ui = mock(UI.class); + when(ui.getUIId()).thenReturn(id); + return ui; + } +} diff --git a/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java b/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java index cfb80b6e388..797a6d464b5 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java @@ -57,6 +57,7 @@ import com.vaadin.tests.util.MockDeploymentConfiguration; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; @@ -446,6 +447,28 @@ void threadLocalsWhenDeserializing() throws Exception { deserializedSession.unlock(); } + @Test + void addUI_uiIsStoredInSessionUIService() { + SessionUIService uiService = mockService.getSessionUIService(); + assertEquals(1, uiService.getUIs(session).size()); + assertSame(ui, uiService.getUIById(session, ui.getUIId())); + assertSame(ui, session.getUIById(ui.getUIId())); + } + + @Test + void fireSessionDestroy_sessionIsRemovedFromSessionUIService() { + SessionUIService uiService = mockService.getSessionUIService(); + assertTrue(uiService.getSessions().contains(session)); + + // Release the lock from setup so that access() runs right away + session.unlock(); + mockService.fireSessionDestroy(session); + + assertEquals(VaadinSessionState.CLOSED, session.getState()); + assertTrue(uiService.getUIs(session).isEmpty()); + assertFalse(uiService.getSessions().contains(session)); + } + @Test void setLocale_setLocaleForAllUIs() { UI anotherUI = new UI(); From 7adf8808b08c5120b36b9e0a8aa7b0a1a48f513b Mon Sep 17 00:00:00 2001 From: OriginalFelix Date: Wed, 28 Oct 2026 13:42:52 +0100 Subject: [PATCH 2/8] docs: remove @since tags from SessionUIService --- .../src/main/java/com/vaadin/flow/server/SessionUIService.java | 2 -- .../src/main/java/com/vaadin/flow/server/VaadinService.java | 1 - 2 files changed, 3 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java b/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java index d8b727025d4..5fa69599ee1 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java @@ -40,8 +40,6 @@ *

* One instance is owned by each {@link VaadinService}, see * {@link VaadinService#getSessionUIService()}. - * - * @since 25.4 */ public class SessionUIService { diff --git a/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java b/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java index daefc3b683f..23d6df99f44 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java @@ -1001,7 +1001,6 @@ public VaadinServiceEventBus getEventBus() { * service. * * @return the session UI service, not {@code null} - * @since 25.4 */ public SessionUIService getSessionUIService() { SessionUIService result = sessionUIService; From 8db6662999c2418fd7a420ddfd4651142ca8dbb0 Mon Sep 17 00:00:00 2001 From: OriginalFelix Date: Wed, 28 Oct 2026 13:42:35 +0100 Subject: [PATCH 3/8] feat: add opt-in locking per UI instead of per session 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. --- .../flow/component/PushConfiguration.java | 2 +- .../java/com/vaadin/flow/component/UI.java | 78 ++++- .../DeadlockDetectingCompletableFuture.java | 7 +- .../flow/component/internal/UIInternals.java | 257 +++++++++++++- .../function/DeploymentConfiguration.java | 22 ++ .../com/vaadin/flow/internal/StateTree.java | 2 +- .../vaadin/flow/router/BeforeLeaveEvent.java | 7 +- .../java/com/vaadin/flow/router/Router.java | 2 +- .../com/vaadin/flow/server/Attributes.java | 4 +- .../vaadin/flow/server/BootstrapHandler.java | 9 + .../vaadin/flow/server/InitParameters.java | 7 + .../flow/server/SessionLockCheckStrategy.java | 41 ++- .../flow/server/StreamResourceRegistry.java | 4 +- .../server/SynchronizedRequestHandler.java | 101 +++++- .../com/vaadin/flow/server/VaadinService.java | 110 +++++- .../com/vaadin/flow/server/VaadinSession.java | 193 ++++++++++- .../communication/HeartbeatHandler.java | 9 +- .../server/communication/PushHandler.java | 38 +- .../communication/StreamReceiverHandler.java | 40 ++- .../communication/StreamRequestHandler.java | 13 +- .../communication/UidlRequestHandler.java | 9 +- .../flow/server/communication/UidlWriter.java | 6 +- .../flow/server/streams/UploadEvent.java | 4 + .../flow/signals/local/ValueSignal.java | 2 +- .../com/vaadin/flow/server/UILockingTest.java | 324 ++++++++++++++++++ .../context/VaadinSessionScopedContext.java | 34 +- .../spring/scopes/SessionLockSupport.java | 58 ++++ .../flow/spring/scopes/VaadinRouteScope.java | 23 +- .../flow/spring/scopes/VaadinUIScope.java | 15 +- 29 files changed, 1315 insertions(+), 106 deletions(-) create mode 100644 flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java create mode 100644 vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/SessionLockSupport.java diff --git a/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java b/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java index d818658eb9c..4bcbffdb5f4 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/PushConfiguration.java @@ -227,7 +227,7 @@ public void setPushMode(PushMode pushMode) { "Cannot set the push mode for a detached UI"); } - session.checkHasLock(); + session.checkHasUIAccess(ui); if (pushMode.isEnabled() && !session.getService().ensurePushAvailable()) { diff --git a/flow-server/src/main/java/com/vaadin/flow/component/UI.java b/flow-server/src/main/java/com/vaadin/flow/component/UI.java index 63f65c5cc56..8b5fc6061fd 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/UI.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/UI.java @@ -84,6 +84,7 @@ import com.vaadin.flow.server.Command; import com.vaadin.flow.server.ErrorEvent; import com.vaadin.flow.server.ErrorHandlingCommand; +import com.vaadin.flow.server.FutureAccess; import com.vaadin.flow.server.HttpStatusCode; import com.vaadin.flow.server.VaadinRequest; import com.vaadin.flow.server.VaadinService; @@ -444,8 +445,11 @@ public void close() { // the UI is detached and cleaned up. // Can't use UI.push() directly since it checks for a valid session - if (getSession() != null) { - getSession().getService().runPendingAccessTasks(getSession()); + VaadinSession session = getSession(); + if (session != null && session.isUILockingEnabled()) { + getInternals().runPendingAccessTasks(); + } else if (session != null) { + session.getService().runPendingAccessTasks(session); } pushConnection.push(); } @@ -594,6 +598,11 @@ private void accessSynchronously(Command command, VaadinService.verifyNoOtherSessionLocked(session); + if (session.isUILockingEnabled()) { + accessSynchronouslyWithUILock(session, command, detachHandler); + return; + } + session.lock(); try { if (getSession() == null) { @@ -613,6 +622,46 @@ private void accessSynchronously(Command command, } + /** + * Runs the command while holding only the lock of this UI, used when the + * session uses UI locking. + */ + private void accessSynchronouslyWithUILock(VaadinSession session, + Command command, SerializableRunnable detachHandler) { + UIInternals internals = getInternals(); + if (!internals.hasUILock() && session.hasAccess()) { + /* + * Threads holding a UI lock may wait for the session lock, so + * waiting for this UI lock while holding the session lock or the + * lock of another UI could deadlock. + */ + if (!internals.tryLockUI()) { + throw new IllegalStateException( + "Cannot synchronously access a UI that is locked by another thread " + + "while holding the session lock or the lock of another UI. " + + "Use UI.access() instead."); + } + } else { + internals.lockUI(); + } + + Map, CurrentInstance> old = null; + try { + if (getSession() == null) { + // UI was detached before the lock was acquired + handleAccessDetach(detachHandler); + return; + } + old = CurrentInstance.setCurrent(this); + command.execute(); + } finally { + internals.unlockUI(); + if (old != null) { + CurrentInstance.restoreInstances(old); + } + } + } + /** * Provides exclusive access to this UI from outside a request handling * thread. @@ -622,6 +671,10 @@ private void accessSynchronously(Command command, * be acquired and the command is run right away. If the session is * currently locked, the command will be run before that lock is released. *

+ * With {@link VaadinSession#isUILockingEnabled() UI locking}, only the lock + * of this UI is held instead of the session lock, and the command is run + * before the UI lock is released. + *

* RPC handlers for components inside this UI do not need to use this method * as the session is automatically locked by the framework during RPC * handling. @@ -671,7 +724,7 @@ private Future access(Command command, return null; } - return session.access(new ErrorHandlingCommand() { + ErrorHandlingCommand task = new ErrorHandlingCommand() { @Override public void execute() { accessSynchronously(command, detachHandler); @@ -711,7 +764,16 @@ public void handleError(Exception exception) { getLogger().error(e.getMessage(), e); } } - }); + }; + + if (session.isUILockingEnabled()) { + // Only this UI needs to be locked, the session lock is not used + FutureAccess future = new FutureAccess(session, task); + getInternals().getPendingAccessQueue().add(future); + getInternals().ensureAccessQueuePurged(); + return future; + } + return session.access(task); } /** @@ -891,7 +953,7 @@ public void push() { if (session == null) { throw new UIDetachedException("Cannot push a detached UI"); } - session.checkHasLock(); + session.checkHasUIAccess(this); if (!getPushConfiguration().getPushMode().isEnabled()) { throw new IllegalStateException("Push not enabled"); @@ -905,7 +967,11 @@ public void push() { * when the push would otherwise be ignored because there are no changes * to push. */ - session.getService().runPendingAccessTasks(session); + if (session.isUILockingEnabled()) { + getInternals().runPendingAccessTasks(); + } else { + session.getService().runPendingAccessTasks(session); + } if (!getInternals().isDirty() || getInternals().getStateTree().isPreparingForResync()) { diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/DeadlockDetectingCompletableFuture.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/DeadlockDetectingCompletableFuture.java index af539f16b2e..9de1a5ac9bb 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/DeadlockDetectingCompletableFuture.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/DeadlockDetectingCompletableFuture.java @@ -80,11 +80,12 @@ private void throwIfDeadlock() { // Won't block if we're done return; } - if (session != null && session.hasLock()) { + if (session != null && (session.hasLock() || session.hasAccess())) { /* * Disallow blocking if the current thread holds the lock for the - * session that would need to be locked by a request thread to - * complete the result + * session, or with UI locking the lock of one of its UIs, that + * would need to be locked by a request thread to complete the + * result */ throw new IllegalStateException( "Cannot block on the value from the thread that has locked the session. " diff --git a/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java b/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java index bbb761d7cc9..242538018c4 100644 --- a/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java +++ b/flow-server/src/main/java/com/vaadin/flow/component/internal/UIInternals.java @@ -29,8 +29,13 @@ import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.Queue; import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -72,6 +77,7 @@ import com.vaadin.flow.internal.BundleUtils; import com.vaadin.flow.internal.CompressUtil; import com.vaadin.flow.internal.ConstantPool; +import com.vaadin.flow.internal.CurrentInstance; import com.vaadin.flow.internal.JacksonCodec; import com.vaadin.flow.internal.StateNode; import com.vaadin.flow.internal.StateTree; @@ -100,6 +106,7 @@ import com.vaadin.flow.router.internal.BeforeEnterHandler; import com.vaadin.flow.router.internal.BeforeLeaveHandler; import com.vaadin.flow.server.FrontendDependencyUrlResolver; +import com.vaadin.flow.server.FutureAccess; import com.vaadin.flow.server.VaadinService; import com.vaadin.flow.server.VaadinSession; import com.vaadin.flow.server.communication.PushConnection; @@ -107,6 +114,7 @@ import com.vaadin.flow.shared.communication.PushMode; import com.vaadin.flow.shared.ui.LoadMode; import com.vaadin.flow.signals.Signal; +import com.vaadin.flow.signals.impl.Transaction; import com.vaadin.flow.signals.local.ValueSignal; /** @@ -301,6 +309,24 @@ public List getParameters() { */ private volatile VaadinSession session; + /** + * Protects the state of the related UI when the session uses UI locking, + * see {@link VaadinSession#isUILockingEnabled()}. Deserialized unlocked. + */ + private final ReentrantLock uiLock = new ReentrantLock(); + + /* + * Tasks enqueued with UI.access() when the session uses UI locking. Pending + * tasks can't be serialized, the queue is recreated lazily. + */ + private transient volatile Queue pendingAccessQueue; + + /* + * Repeatable-read transaction for shared signals while the UI lock is held, + * the UI locking counterpart of the session-scoped transaction. + */ + private transient Transaction uiScopedTransaction; + private final DependencyList dependencyList = new DependencyList(); private final Set pendingStyleSheetRemovals = new LinkedHashSet<>(); @@ -570,7 +596,7 @@ public Instant getLastUpdateSentTimestamp() { */ // Package private: only used through PendingJavaScriptInvocationUtil int addUndeliveredJsInvocations(int delta) { - session.checkHasLock(); + session.checkHasUIAccess(ui); // Only an invocation that this instance counted uncounts itself, so // the count is not expected to go negative. Clamped rather than // asserted since a slip in the bookkeeping behind a warning is not @@ -590,7 +616,7 @@ int addUndeliveredJsInvocations(int delta) { */ // Package private: only used through PendingJavaScriptInvocationUtil boolean markUndeliveredJsInvocationsWarningLogged() { - session.checkHasLock(); + session.checkHasUIAccess(ui); if (undeliveredJsInvocationsWarningLogged) { return false; } @@ -645,6 +671,221 @@ private static String getSessionDetails(VaadinSession session) { } } + /** + * Checks whether the current thread holds the lock of the related UI. The + * UI lock is only used when the session uses UI locking, see + * {@link VaadinSession#isUILockingEnabled()}. + *

+ * This method is meant for framework internal use. + * + * @return {@code true} if the current thread holds the UI lock + */ + public boolean hasUILock() { + return uiLock.isHeldByCurrentThread(); + } + + /** + * Checks whether the current thread may access the state of the related UI: + * it holds the UI lock with UI locking, or the session lock otherwise. + * Returns {@code false} if the UI is not attached to a session. + * + * @return {@code true} if the UI state may be accessed + */ + public boolean hasAccess() { + VaadinSession currentSession = session; + if (currentSession == null) { + return false; + } + return currentSession.isUILockingEnabled() ? hasUILock() + : currentSession.hasLock(); + } + + /** + * Gets the lock protecting the related UI when the session uses UI locking. + * Use {@link #lockUI()} and {@link #unlockUI()} instead of locking it + * directly, so that pending tasks are run and changes pushed on release. + *

+ * This method is meant for framework internal use. + * + * @return the UI lock, not {@code null} + */ + public ReentrantLock getUILock() { + return uiLock; + } + + /** + * Acquires the UI lock, blocking until it is available. + *

+ * Must not be called while holding the session lock or the lock of another + * UI, since threads holding a UI lock may wait for the session lock. Use + * {@link #tryLockUI()} in that case. + *

+ * This method is meant for framework internal use. + */ + public void lockUI() { + uiLock.lock(); + } + + /** + * Acquires the UI lock if it is free or already held by the current thread, + * without waiting. + *

+ * This method is meant for framework internal use. + * + * @return {@code true} if the lock was acquired and must be released with + * {@link #unlockUI()} + */ + public boolean tryLockUI() { + return uiLock.tryLock(); + } + + /** + * Releases the UI lock. When the lock is ultimately released, tasks + * enqueued with {@link UI#access(com.vaadin.flow.server.Command)} are run + * and pending changes are pushed if push mode is {@link PushMode#AUTOMATIC + * automatic}. + *

+ * This method is meant for framework internal use. + */ + public void unlockUI() { + boolean ultimateRelease = false; + try { + if (uiLock.getHoldCount() == 1) { + ultimateRelease = true; + runPendingAccessTasks(); + pushIfAutomatic(); + uiScopedTransaction = null; + } + } finally { + uiLock.unlock(); + } + /* + * A task may be enqueued after the queue was purged but before the lock + * was released, see VaadinSession.unlock(). + */ + if (ultimateRelease && !getPendingAccessQueue().isEmpty()) { + ensureAccessQueuePurged(); + } + } + + private void pushIfAutomatic() { + if (session == null || ui.getPushConfiguration() + .getPushMode() != PushMode.AUTOMATIC) { + return; + } + Map, CurrentInstance> oldCurrent = CurrentInstance + .setCurrent(ui); + try { + ui.push(); + } finally { + CurrentInstance.restoreInstances(oldCurrent); + } + } + + /** + * Gets the queue of tasks enqueued with + * {@link UI#access(com.vaadin.flow.server.Command)} when the session uses + * UI locking. It is safe to access the queue without holding any lock. + *

+ * This method is meant for framework internal use. + * + * @return the queue of pending access tasks, not {@code null} + */ + public Queue getPendingAccessQueue() { + Queue queue = pendingAccessQueue; + if (queue == null) { + synchronized (uiLock) { + queue = pendingAccessQueue; + if (queue == null) { + queue = new ConcurrentLinkedQueue<>(); + pendingAccessQueue = queue; + } + } + } + return queue; + } + + /** + * Runs the pending access tasks if the UI lock is free, or leaves them to + * the thread holding the lock, which runs them before releasing it. + *

+ * This method is meant for framework internal use. + */ + public void ensureAccessQueuePurged() { + try { + // tryLock() would be shorter, but it does not guarantee fairness + if (uiLock.tryLock(0, TimeUnit.SECONDS)) { + // unlockUI triggers runPendingAccessTasks + unlockUI(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + /** + * Runs the tasks enqueued with + * {@link UI#access(com.vaadin.flow.server.Command)} when the session uses + * UI locking. Does nothing if the current thread does not hold the UI lock, + * since the tasks are then run when the lock is released. + *

+ * This method is meant for framework internal use. + */ + public void runPendingAccessTasks() { + if (!hasUILock()) { + // Run by the thread holding the UI lock when releasing it + return; + } + Queue queue = getPendingAccessQueue(); + if (queue.isEmpty()) { + return; + } + // Dump all current instances, not only the ones dumped by setCurrent + Map, CurrentInstance> oldInstances = CurrentInstance + .getInstances(); + try { + FutureAccess pendingAccess; + while ((pendingAccess = queue.poll()) != null) { + if (!pendingAccess.isCancelled()) { + CurrentInstance.clearAll(); + VaadinSession currentSession = session; + if (currentSession != null) { + CurrentInstance.setCurrent(currentSession); + } + // Fresh reads from shared signals for each task + uiScopedTransaction = null; + pendingAccess.run(); + try { + pendingAccess.get(); + } catch (CancellationException ignored) { // NOSONAR + // Canceled tasks are not reported to the error handler + } catch (Exception exception) { + pendingAccess.handleError(exception); + } + } + } + } finally { + CurrentInstance.clearAll(); + CurrentInstance.restoreInstances(oldInstances); + } + } + + /** + * Gets the transaction used for shared signal operations while the UI lock + * is held, creating it lazily. The UI lock must be held. + *

+ * This method is meant for framework internal use. + * + * @return the UI-scoped transaction, not {@code null} + */ + public Transaction getOrCreateUIScopedTransaction() { + assert hasUILock(); + if (uiScopedTransaction == null) { + uiScopedTransaction = Transaction.createWriteThrough(); + } + return uiScopedTransaction; + } + /** * Sets the session to which the related UI is assigned. *

@@ -773,7 +1014,7 @@ public Registration addHeartbeatListener(HeartbeatListener listener) { } private Registration addListener(Class handler, E listener) { - session.checkHasLock(); + session.checkHasUIAccess(ui); List list = (List) listeners.computeIfAbsent(handler, key -> new ArrayList<>()); list.add(listener); @@ -828,7 +1069,7 @@ public List getListeners(Class handler) { */ public void addJavaScriptInvocation( PendingJavaScriptInvocation invocation) { - session.checkHasLock(); + session.checkHasUIAccess(ui); pendingJsInvocations.add(invocation); pendingJsInvocationOwners.add(invocation.getOwner()); // Counts an invocation that is queued directly, such as one from @@ -902,7 +1143,7 @@ public PendingJavaScriptResult addJavaScriptInvocation(StateNode owner, * @since 25.2 */ public int nextJsInitializerId() { - session.checkHasLock(); + session.checkHasUIAccess(ui); return nextJsInitializerId++; } @@ -914,7 +1155,7 @@ public int nextJsInitializerId() { * @return a list of pending JavaScript invocations */ public List dumpPendingJavaScriptInvocations() { - session.checkHasLock(); + session.checkHasUIAccess(ui); pendingTitleUpdateCanceler = null; lastUpdateSentTimestamp = Instant.now(); @@ -988,7 +1229,7 @@ public void discardPendingJavaScriptInvocations() { */ private void checkInvocationQueueLock() { if (session != null) { - session.checkHasLock(); + session.checkHasUIAccess(ui); } } @@ -1001,7 +1242,7 @@ private void checkInvocationQueueLock() { */ // Non-private for testing purposes Stream getPendingJavaScriptInvocations() { - session.checkHasLock(); + session.checkHasUIAccess(ui); return pendingJsInvocations.stream() .filter(invocation -> !invocation.isCanceled()); } diff --git a/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java b/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java index 3f210b770ce..b00fb3941ac 100644 --- a/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java +++ b/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java @@ -433,6 +433,28 @@ default boolean isReactEnabled() { return getBooleanProperty(InitParameters.REACT_ENABLE, true); } + /** + * Checks whether UI state is protected by a lock per UI instead of the + * session lock. + *

+ * When enabled, request handling and {@code UI.access} for a UI only lock + * that UI and never block on the session lock, so UIs of the same session + * are updated in parallel. Session state such as attributes stays + * accessible while holding a UI lock but is no longer protected against + * concurrent access from other UIs of the same session. + *

+ * The setting is configured with + * {@link InitParameters#SERVLET_PARAMETER_UI_LOCKING}. By default, it + * returns {@code false}. + * + * @return {@code true} if UI locking is enabled, {@code false} if the + * session lock is used + */ + default boolean isUILockingEnabled() { + return getBooleanProperty( + InitParameters.SERVLET_PARAMETER_UI_LOCKING, false); + } + /** * Checks whether the theme styles plain HTML elements, such as a * <table>, across the whole application. diff --git a/flow-server/src/main/java/com/vaadin/flow/internal/StateTree.java b/flow-server/src/main/java/com/vaadin/flow/internal/StateTree.java index 16ca56ba99e..c563ad4fa93 100644 --- a/flow-server/src/main/java/com/vaadin/flow/internal/StateTree.java +++ b/flow-server/src/main/java/com/vaadin/flow/internal/StateTree.java @@ -481,7 +481,7 @@ public boolean isDirty() { private void checkHasLock() { VaadinSession session = uiInternals.getSession(); if (session != null) { - session.checkHasLock(); + session.checkHasUIAccess(uiInternals.getUI()); } } diff --git a/flow-server/src/main/java/com/vaadin/flow/router/BeforeLeaveEvent.java b/flow-server/src/main/java/com/vaadin/flow/router/BeforeLeaveEvent.java index 659063d90fc..65a3d4e792a 100644 --- a/flow-server/src/main/java/com/vaadin/flow/router/BeforeLeaveEvent.java +++ b/flow-server/src/main/java/com/vaadin/flow/router/BeforeLeaveEvent.java @@ -56,10 +56,10 @@ private ContinueNavigationAction() { public void setReferences(NavigationHandler handler, NavigationEvent event) { if (event != null) { - event.getUI().getSessionOrThrow().hasLock(); + event.getUI().getSessionOrThrow(); } else { assert UI.getCurrent() != null - && UI.getCurrent().getSessionOrThrow().hasLock(); + && UI.getCurrent().getInternals().hasAccess(); } this.handler = handler; this.event = event; @@ -74,7 +74,8 @@ public void setReferences(NavigationHandler handler, public void proceed() { BeforeLeaveEvent.this.continueNavigationAction = null; if (handler != null && event != null) { - if (!event.getUI().getSessionOrThrow().hasLock()) { + event.getUI().getSessionOrThrow(); + if (!event.getUI().getInternals().hasAccess()) { throw new IllegalStateException( "The method 'proceed' may not be called without the session lock. " + "Use UI.access() to execute any UI related code from a separate thread properly"); diff --git a/flow-server/src/main/java/com/vaadin/flow/router/Router.java b/flow-server/src/main/java/com/vaadin/flow/router/Router.java index faa894c4dfa..d02b34e36ba 100644 --- a/flow-server/src/main/java/com/vaadin/flow/router/Router.java +++ b/flow-server/src/main/java/com/vaadin/flow/router/Router.java @@ -402,7 +402,7 @@ public int navigate(UI ui, Location location, NavigationTrigger trigger, assert ui != null; assert location != null; assert trigger != null; - ui.getSessionOrThrow().checkHasLock(); + ui.getSessionOrThrow().checkHasUIAccess(ui); if (handleNavigationForLocation(ui, location)) { return observeNavigation(ui, location, trigger, () -> { diff --git a/flow-server/src/main/java/com/vaadin/flow/server/Attributes.java b/flow-server/src/main/java/com/vaadin/flow/server/Attributes.java index c82fdbdd558..f35ee979103 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/Attributes.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/Attributes.java @@ -16,7 +16,7 @@ package com.vaadin.flow.server; import java.io.Serializable; -import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; /** * The {@link Attributes} class represents a set of attributes. @@ -27,7 +27,7 @@ */ public class Attributes implements Serializable { - private final HashMap attributes = new HashMap<>(); + private final ConcurrentHashMap attributes = new ConcurrentHashMap<>(); /** * Stores a value in this set. diff --git a/flow-server/src/main/java/com/vaadin/flow/server/BootstrapHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/BootstrapHandler.java index c751925ace3..33affb172ff 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/BootstrapHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/BootstrapHandler.java @@ -1288,6 +1288,15 @@ protected BootstrapContext createAndInitUI(Class uiClass, VaadinSession session) { UI ui = ReflectTools.createInstance(uiClass); + if (session.isUILockingEnabled()) { + /* + * The new UI is not reachable by other threads yet, so this never + * waits. Released by SynchronizedRequestHandler together with the + * session lock. + */ + boolean locked = ui.getInternals().tryLockUI(); + assert locked : "A new UI must not be locked by another thread"; + } ui.getInternals().setContextRoot( request.getService().getContextRootRelativePath(request)); diff --git a/flow-server/src/main/java/com/vaadin/flow/server/InitParameters.java b/flow-server/src/main/java/com/vaadin/flow/server/InitParameters.java index 9c70866b6ca..77596fb85a8 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/InitParameters.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/InitParameters.java @@ -51,6 +51,13 @@ public class InitParameters implements Serializable { public static final String SERVLET_PARAMETER_CLOSE_IDLE_SESSIONS = "closeIdleSessions"; public static final String SERVLET_PARAMETER_PUSH_MODE = "pushMode"; public static final String SERVLET_PARAMETER_SESSION_LOCK_CHECK_STRATEGY = "sessionLockCheckStrategy"; + /** + * Configuration parameter name for enabling locking per {@code UI} instead + * of per {@code VaadinSession}. When enabled, updating a UI only locks that + * UI, so UIs of the same session (e.g. browser tabs) are updated in + * parallel. The default is {@code false}. + */ + public static final String SERVLET_PARAMETER_UI_LOCKING = "uiLocking"; public static final String SERVLET_PARAMETER_PUSH_SERVLET_MAPPING = "pushServletMapping"; public static final String SERVLET_PARAMETER_SYNC_ID_CHECK = "syncIdCheck"; public static final String SERVLET_PARAMETER_SEND_URLS_AS_PARAMETERS = "sendUrlsAsParameters"; diff --git a/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java b/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java index 068281706bc..672dc7863d3 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java @@ -15,6 +15,8 @@ */ package com.vaadin.flow.server; +import java.util.function.BooleanSupplier; + /** * Available strategies for session lock checking. * @@ -27,8 +29,9 @@ public enum SessionLockCheckStrategy { */ ASSERT { @Override - public void checkHasLock(VaadinSession session, String message) { - assert session.hasLock() : message; + public void checkHasLock(BooleanSupplier hasLock, + VaadinSession session, String message) { + assert hasLock.getAsBoolean() : message; } }, /** @@ -37,8 +40,9 @@ public void checkHasLock(VaadinSession session, String message) { */ LOG { @Override - public void checkHasLock(VaadinSession session, String message) { - if (!session.hasLock()) { + public void checkHasLock(BooleanSupplier hasLock, + VaadinSession session, String message) { + if (!hasLock.getAsBoolean()) { session.getLogger().warn(message, new IllegalStateException(message)); } @@ -50,8 +54,9 @@ public void checkHasLock(VaadinSession session, String message) { */ THROW { @Override - public void checkHasLock(VaadinSession session, String message) { - if (!session.hasLock()) { + public void checkHasLock(BooleanSupplier hasLock, + VaadinSession session, String message) { + if (!hasLock.getAsBoolean()) { throw new IllegalStateException(message); } } @@ -59,7 +64,9 @@ public void checkHasLock(VaadinSession session, String message) { /** * Potentially checks whether this session is currently locked by the - * current thread + * current thread. With {@link VaadinSession#isUILockingEnabled() UI + * locking}, holding the lock of one of the session's UIs is also accepted, + * see {@link VaadinSession#hasAccess()}. * * @param session * the session to check the lock for, not null. @@ -67,5 +74,23 @@ public void checkHasLock(VaadinSession session, String message) { * the error message to include when failing if the check is done * and the session is not locked */ - public abstract void checkHasLock(VaadinSession session, String message); + public void checkHasLock(VaadinSession session, String message) { + checkHasLock(session::hasAccess, session, message); + } + + /** + * Potentially checks whether the current thread holds a lock, and fails + * according to this strategy if not. + * + * @param hasLock + * evaluates whether the required lock is held, only invoked if + * the check is done, not null + * @param session + * the session the lock belongs to, not null + * @param message + * the error message to include when failing if the check is done + * and the lock is not held + */ + public abstract void checkHasLock(BooleanSupplier hasLock, + VaadinSession session, String message); } diff --git a/flow-server/src/main/java/com/vaadin/flow/server/StreamResourceRegistry.java b/flow-server/src/main/java/com/vaadin/flow/server/StreamResourceRegistry.java index 72ad65f2534..3ef50d1fcd4 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/StreamResourceRegistry.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/StreamResourceRegistry.java @@ -18,9 +18,9 @@ import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; -import java.util.HashMap; import java.util.Map; import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; import com.vaadin.flow.component.UI; import com.vaadin.flow.dom.Element; @@ -35,7 +35,7 @@ */ public class StreamResourceRegistry implements Serializable { - private final Map res = new HashMap<>(); + private final Map res = new ConcurrentHashMap<>(); private final VaadinSession session; diff --git a/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java index cf51a7ffac4..96a4ec05b2c 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java @@ -23,6 +23,9 @@ import org.slf4j.LoggerFactory; +import com.vaadin.flow.component.UI; +import com.vaadin.flow.component.internal.UIInternals; + /** * RequestHandler which takes care of locking and unlocking of the VaadinSession * automatically. The session is locked before @@ -58,6 +61,14 @@ public boolean handleRequest(VaadinSession session, VaadinRequest request, return false; } + if (session.isUILockingEnabled() && canHandleWithUILock()) { + UI ui = session.getService().findUI(session, request); + if (ui != null) { + return handleRequestWithUILock(session, ui, request, response); + } + // UI not found: let the handler respond as before + } + try { if (isReadAndWriteOutsideSessionLock()) { BufferedReader reader = request.getReader(); @@ -70,8 +81,13 @@ public boolean handleRequest(VaadinSession session, VaadinRequest request, return rejectOversizedRequest(response, e); } session.lock(); - Optional responseWriter = synchronizedHandleRequest( - session, request, response, requestBody); + Optional responseWriter; + try { + responseWriter = synchronizedHandleRequest(session, + request, response, requestBody); + } finally { + releaseUILocks(session); + } session.unlock(); if (responseWriter.isPresent()) { responseWriter.get().writeResponse(); @@ -79,7 +95,12 @@ public boolean handleRequest(VaadinSession session, VaadinRequest request, return responseWriter.isPresent(); } else { session.lock(); - return synchronizedHandleRequest(session, request, response); + try { + return synchronizedHandleRequest(session, request, + response); + } finally { + releaseUILocks(session); + } } } finally { if (session.hasLock()) { @@ -88,6 +109,80 @@ public boolean handleRequest(VaadinSession session, VaadinRequest request, } } + /** + * Handles the request for the given UI while holding only the UI lock, used + * with {@link VaadinSession#isUILockingEnabled() UI locking}. + */ + private boolean handleRequestWithUILock(VaadinSession session, UI ui, + VaadinRequest request, VaadinResponse response) + throws IOException { + UIInternals internals = ui.getInternals(); + if (isReadAndWriteOutsideSessionLock()) { + BufferedReader reader = request.getReader(); + String requestBody; + try { + requestBody = reader == null ? null + : getRequestBody(reader, + getMaxRequestBodySize(request)); + } catch (RequestBodyTooLargeException e) { + return rejectOversizedRequest(response, e); + } + Optional responseWriter; + internals.lockUI(); + try { + responseWriter = synchronizedHandleRequest(session, request, + response, requestBody); + } finally { + internals.unlockUI(); + } + if (responseWriter.isPresent()) { + responseWriter.get().writeResponse(); + } + return responseWriter.isPresent(); + } + internals.lockUI(); + try { + return synchronizedHandleRequest(session, request, response); + } finally { + internals.unlockUI(); + } + } + + /** + * Releases UI locks the current thread acquired while handling the request + * with the session lock, e.g. for a UI created during bootstrap. Must be + * called before the session lock is released. + */ + private static void releaseUILocks(VaadinSession session) { + if (!session.isUILockingEnabled()) { + return; + } + for (UI ui : session.getUIs()) { + UIInternals internals = ui.getInternals(); + while (internals.hasUILock()) { + internals.unlockUI(); + } + } + } + + /** + * Checks whether the request targets a single UI and can therefore be + * handled while holding only the lock of that UI instead of the session + * lock, when the session uses {@link VaadinSession#isUILockingEnabled() UI + * locking}. The UI is resolved with + * {@link VaadinService#findUI(VaadinSession, VaadinRequest)}. If no UI is + * found, the request is handled with the session lock. + *

+ * Handlers returning {@code true} must only access the state of that UI and + * thread-safe session state. + * + * @return {@code true} if the UI lock is sufficient, {@code false} by + * default + */ + protected boolean canHandleWithUILock() { + return false; + } + /** * Identical to * {@link #handleRequest(VaadinSession, VaadinRequest, VaadinResponse)} diff --git a/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java b/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java index 23d6df99f44..02393cfb67c 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/VaadinService.java @@ -62,6 +62,7 @@ import com.vaadin.flow.component.UI; import com.vaadin.flow.component.UIDetachedException; +import com.vaadin.flow.component.internal.UIInternals; import com.vaadin.flow.di.DefaultInstantiator; import com.vaadin.flow.di.Instantiator; import com.vaadin.flow.di.InstantiatorFactory; @@ -584,11 +585,20 @@ public Executor getEffectDispatcher() { Transaction.setTransactionFallback(() -> { VaadinSession session = VaadinSession.getCurrent(); - if (session == null || session.getLockInstance() == null - || !session.hasLock()) { + if (session == null || session.getLockInstance() == null) { return null; } - return session.getOrCreateSessionScopedTransaction(); + if (session.hasLock()) { + return session.getOrCreateSessionScopedTransaction(); + } + if (session.isUILockingEnabled()) { + UI ui = UI.getCurrent(); + if (ui != null && ui.getInternals().getSession() == session + && ui.getInternals().hasUILock()) { + return ui.getInternals().getOrCreateUIScopedTransaction(); + } + } + return null; }); addServiceDestroyListener(event -> { @@ -1178,7 +1188,7 @@ public void fireSessionDestroy(VaadinSession vaadinSession) { for (final UI ui : uis) { try { ui.getInternals().terminateActiveTransfers(); - ui.accessSynchronously(() -> { + accessUIWithoutWaiting(session, ui, true, () -> { /* * close() called here for consistency so that it is * always called before a UI is removed. UI.isClosing() @@ -1493,6 +1503,8 @@ private VaadinSession createAndRegisterSession(VaadinRequest request) { : SessionLockCheckStrategy.THROW; assert sessionLockCheckStrategy != null; session.applyLockStrategy(sessionLockCheckStrategy); + session.applyUILocking( + getDeploymentConfiguration().isUILockingEnabled()); // Initial locale comes from the request if (getInstantiator().getI18NProvider() != null) { @@ -1742,6 +1754,39 @@ public UI findUI(VaadinRequest request) { return ui; } + /** + * Finds the UI that belongs to the request in the given session and sets it + * as the current UI. + *

+ * With {@link VaadinSession#isUILockingEnabled() UI locking}, no lock is + * required and the UI is looked up directly in the given session. + * Otherwise, this delegates to {@link #findUI(VaadinRequest)}, which + * requires the session lock. + * + * @param session + * the session the request belongs to, may be {@code null} + * @param request + * the request to find a UI for + * @return the UI, or {@code null} if not found + */ + public UI findUI(VaadinSession session, VaadinRequest request) { + if (session == null || !session.isUILockingEnabled()) { + return findUI(request); + } + String uiIdString = request + .getParameter(ApplicationConstants.UI_ID_PARAMETER); + UI ui = null; + if (uiIdString != null) { + try { + ui = session.findUIWithoutLock(Integer.parseInt(uiIdString)); + } catch (NumberFormatException e) { + getLogger().debug("Invalid UI id {}", uiIdString); + } + } + UI.setCurrent(ui); + return ui; + } + /** * Discards the current session and creates a new session with the same * contents. The purpose of this is to introduce a new session key in order @@ -1906,7 +1951,7 @@ private void removeClosedUIs(final VaadinSession session) { ui.getUIId()); continue; } - ui.accessSynchronously(() -> { + accessUIWithoutWaiting(session, ui, false, () -> { getLogger().debug("Removing closed UI {}", ui.getUIId()); session.removeUI(ui); }); @@ -1914,6 +1959,47 @@ private void removeClosedUIs(final VaadinSession session) { } } + /** + * Runs a task that accesses the given UI from a thread that may hold the + * session lock. With UI locking, the UI lock is never waited for, since + * threads holding a UI lock may wait for the session lock: if the UI is + * locked by another thread, the task is either enqueued with + * {@link UI#access(Command)} or skipped. + * + * @param session + * the session of the UI + * @param ui + * the UI to access + * @param deferIfBusy + * {@code true} to enqueue the task if the UI is locked by + * another thread, {@code false} to skip it + * @param task + * the task to run + */ + private void accessUIWithoutWaiting(VaadinSession session, UI ui, + boolean deferIfBusy, Command task) { + if (!session.isUILockingEnabled()) { + ui.accessSynchronously(task); + return; + } + UIInternals internals = ui.getInternals(); + if (!internals.tryLockUI()) { + if (deferIfBusy) { + ui.access(task); + } else { + getLogger().debug( + "Skipping cleanup of UI {} which is locked by another thread", + ui.getUIId()); + } + return; + } + try { + ui.accessSynchronously(task); + } finally { + internals.unlockUI(); + } + } + /** * Closes those UIs in the given session for which {@link #isUIActive} * yields false. @@ -1922,7 +2008,7 @@ private void closeInactiveUIs(VaadinSession session) { final String sessionId = session.getSession().getId(); for (final UI ui : session.getUIs()) { if (!isUIActive(ui) && !ui.isClosing()) { - ui.accessSynchronously(() -> { + accessUIWithoutWaiting(session, ui, false, () -> { getLogger().debug("Closing inactive UI #{} in session {}", ui.getUIId(), sessionId); ui.close(); @@ -2002,6 +2088,11 @@ public boolean isUIActive(UI ui) { */ return true; } + ReentrantLock uiLock = ui.getInternals().getUILock(); + if (uiLock.isLocked() || uiLock.hasQueuedThreads()) { + // The UI is being accessed, see above + return true; + } // Check timeout long now = System.currentTimeMillis(); @@ -2748,6 +2839,13 @@ public void ensureAccessQueuePurged(VaadinSession session) { * the vaadin session to purge the queue for */ public void runPendingAccessTasks(VaadinSession session) { + if (session.isUILockingEnabled() && !session.hasLock()) { + /* + * Only holding a UI lock: session tasks must not run without the + * session lock. They run when the session lock is released. + */ + return; + } session.checkHasLock(); if (session.getPendingAccessQueue().isEmpty()) { diff --git a/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java b/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java index 9f02585059d..a6cdffd8c09 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/VaadinSession.java @@ -27,7 +27,6 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; @@ -38,6 +37,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -45,6 +45,7 @@ import org.slf4j.LoggerFactory; import com.vaadin.flow.component.UI; +import com.vaadin.flow.component.internal.UIInternals; import com.vaadin.flow.component.page.Page; import com.vaadin.flow.dom.Element; import com.vaadin.flow.function.DeploymentConfiguration; @@ -78,6 +79,7 @@ public class VaadinSession implements HttpSessionBindingListener, Serializable { private static final String SESSION_NOT_LOCKED_MESSAGE = "Cannot access state in VaadinSession or UI without locking the session."; + private static final String UI_NOT_LOCKED_MESSAGE = "Cannot access state in UI without locking the UI. Use UI.access() to execute UI related code from a separate thread."; private static final Logger LOGGER = LoggerFactory .getLogger(VaadinSession.class.getName()); @@ -89,7 +91,7 @@ public class VaadinSession implements HttpSessionBindingListener, Serializable { * Locale value used for serialization. The signal is the runtime source of * truth; this field is only used to persist the value across serialization. */ - private Locale locale = Locale.getDefault(); + private volatile Locale locale = Locale.getDefault(); private transient ValueSignal localeSignal = new ValueSignal<>( locale); @@ -98,10 +100,10 @@ public class VaadinSession implements HttpSessionBindingListener, Serializable { * Session wide error handler which is used by default if an error is left * unhandled. */ - private ErrorHandler errorHandler = new DefaultErrorHandler(); - private LinkedList requestHandlers = new LinkedList<>(); + private volatile ErrorHandler errorHandler = new DefaultErrorHandler(); + private final CopyOnWriteArrayList requestHandlers = new CopyOnWriteArrayList<>(); - private int nextUIId = 0; + private final AtomicInteger nextUIId = new AtomicInteger(); /* * Holds the UIs while no SessionUIService of a VaadinService is reachable, @@ -110,15 +112,15 @@ public class VaadinSession implements HttpSessionBindingListener, Serializable { */ private transient SessionUIService localUIService; - protected WebBrowser browser = new WebBrowser(); + protected volatile WebBrowser browser = new WebBrowser(); - private long cumulativeRequestDuration = 0; + private volatile long cumulativeRequestDuration = 0; - private long lastRequestDuration = -1; + private volatile long lastRequestDuration = -1; - private long lastRequestTimestamp = System.currentTimeMillis(); + private volatile long lastRequestTimestamp = System.currentTimeMillis(); - private VaadinSessionState state = VaadinSessionState.OPEN; + private volatile VaadinSessionState state = VaadinSessionState.OPEN; private transient WrappedSession session; @@ -128,6 +130,8 @@ public class VaadinSession implements HttpSessionBindingListener, Serializable { private SessionLockCheckStrategy sessionLockCheckStrategy = SessionLockCheckStrategy.ASSERT; + private boolean uiLockingEnabled; + /* * Pending tasks can't be serialized and the queue should be empty when the * session is serialized as long as it doesn't happen while some other @@ -166,6 +170,146 @@ final protected void applyLockStrategy(SessionLockCheckStrategy strategy) { this.sessionLockCheckStrategy = Objects.requireNonNull(strategy); } + /** + * Enables or disables locking per UI for this session, see + * {@link DeploymentConfiguration#isUILockingEnabled()}. Must be called + * before any UI is added to the session. + * + * @param uiLockingEnabled + * {@code true} to protect UI state with a lock per UI, + * {@code false} to use the session lock + */ + final protected void applyUILocking(boolean uiLockingEnabled) { + this.uiLockingEnabled = uiLockingEnabled; + } + + /** + * Checks whether the state of the UIs in this session is protected by a + * lock per UI instead of the session lock. + *

+ * With UI locking, updating a UI (request handling and + * {@link UI#access(Command)}) only locks that UI and never blocks on the + * session lock. Code holding the session lock never blocks on a UI lock. + * Session state stays accessible while holding the lock of one of the + * session's UIs, see {@link #hasAccess()}. + * + * @return {@code true} if UI locking is enabled + * @see DeploymentConfiguration#isUILockingEnabled() + */ + public boolean isUILockingEnabled() { + return uiLockingEnabled; + } + + /** + * Checks whether the current thread may access the state of this session. + * This is the case if it holds the session lock, or, with + * {@link #isUILockingEnabled() UI locking}, the lock of one of the UIs of + * this session. + * + * @return {@code true} if the current thread may access session state + */ + public boolean hasAccess() { + if (hasLock()) { + return true; + } + if (!uiLockingEnabled) { + return false; + } + UI current = UI.getCurrent(); + if (current != null && current.getInternals().getSession() == this + && current.getInternals().hasUILock()) { + return true; + } + for (UI ui : getUIService().getUIs(this)) { + if (ui.getInternals().hasUILock()) { + return true; + } + } + return false; + } + + /** + * Potentially checks whether the current thread may access the state of the + * given UI, and fails with a standard error message if not. + *

+ * With {@link #isUILockingEnabled() UI locking}, the lock of the UI must be + * held. Otherwise, the session lock must be held. Whether and how the check + * is done is decided by the lock check strategy, see + * {@link #checkHasLock()}. + * + * @param ui + * the UI to check, not {@code null} + */ + public void checkHasUIAccess(UI ui) { + if (uiLockingEnabled) { + sessionLockCheckStrategy.checkHasLock( + () -> ui.getInternals().hasUILock(), this, + UI_NOT_LOCKED_MESSAGE); + } else { + checkHasLock(); + } + } + + /** + * Gets a UI by id without requiring any lock. The returned UI must only be + * accessed while holding its lock, see {@link #isUILockingEnabled()}. + * + * @param uiId + * the UI id + * @return the UI, or {@code null} if not found + */ + public UI findUIWithoutLock(int uiId) { + return getUIService().getUIById(this, uiId); + } + + /** + * Gets the UIs of this session without requiring any lock. The returned UIs + * must only be accessed while holding their lock, see + * {@link #isUILockingEnabled()}. + * + * @return an unmodifiable, thread-safe view of the UIs + */ + public Collection getUIsWithoutLock() { + return getUIService().getUIs(this); + } + + /** + * Acquires the lock needed for accessing the state of the given UI: its UI + * lock if the session uses {@link #isUILockingEnabled() UI locking}, the + * session lock otherwise or if the UI is {@code null} or not attached to + * the session. + *

+ * With UI locking, this must not be called while holding the session lock + * or the lock of another UI, see {@link UIInternals#lockUI()}. + *

+ * Usage: + * + *

+     * Runnable unlock = VaadinSession.lockForUI(session, ui);
+     * try {
+     *     // access the UI
+     * } finally {
+     *     unlock.run();
+     * }
+     * 
+ * + * @param session + * the session, not {@code null} + * @param ui + * the UI to lock, may be {@code null} + * @return the action that releases the acquired lock, not {@code null} + */ + public static Runnable lockForUI(VaadinSession session, UI ui) { + if (session.isUILockingEnabled() && ui != null + && ui.getInternals().getSession() == session) { + UIInternals internals = ui.getInternals(); + internals.lockUI(); + return internals::unlockUI; + } + session.lock(); + return session::unlock; + } + /** * Creates the StreamResourceRegistry for this session. * @@ -436,6 +580,10 @@ public Signal localeSignal() { *

* Setting the locale of a session will also override any custom locale * configured for all UIs in this session. + *

+ * With {@link #isUILockingEnabled() UI locking}, UIs whose lock is not held + * by the current thread are updated asynchronously using + * {@link UI#access(Command)}. * * @param locale * the locale to set, not null @@ -448,6 +596,14 @@ public void setLocale(Locale locale) { localeSignal.set(locale); getUIs().forEach(ui -> { + if (uiLockingEnabled && !ui.getInternals().hasUILock()) { + /* + * Never wait for another UI lock here: the caller may hold the + * session lock or the lock of another UI. + */ + ui.access(() -> ui.setLocale(locale)); + return; + } Map, CurrentInstance> oldInstances = CurrentInstance .setCurrent(ui); try { @@ -495,7 +651,7 @@ public void setErrorHandler(ErrorHandler errorHandler) { */ public void addRequestHandler(RequestHandler handler) { checkHasLock(); - requestHandlers.addFirst(handler); + requestHandlers.add(0, handler); } /** @@ -827,7 +983,8 @@ public void lock() { * @see UI#push() */ public void unlock() { - checkHasLock(); + sessionLockCheckStrategy.checkHasLock(this::hasLock, this, + SESSION_NOT_LOCKED_MESSAGE); boolean ultimateRelease = false; try { /* @@ -838,7 +995,15 @@ public void unlock() { ultimateRelease = true; getService().runPendingAccessTasks(this); - for (UI ui : getUIs()) { + /* + * With UI locking, pending UI changes are pushed when the UI + * lock is released. Pushing here would need the UI locks, which + * must not be waited for while holding the session lock. + */ + Collection uisToPush = uiLockingEnabled + ? Collections.emptyList() + : getUIs(); + for (UI ui : uisToPush) { if (ui.getPushConfiguration() .getPushMode() == PushMode.AUTOMATIC) { Map, CurrentInstance> oldCurrent = CurrentInstance @@ -963,7 +1128,7 @@ public T getAttribute(Class type) { */ public int getNextUIid() { checkHasLock(); - return nextUIId++; + return nextUIId.getAndIncrement(); } /** diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/HeartbeatHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/HeartbeatHandler.java index 2bcf5c169b0..e2ae2e80ab1 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/HeartbeatHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/HeartbeatHandler.java @@ -50,6 +50,11 @@ protected boolean canHandleRequest(VaadinRequest request) { return HandlerHelper.isRequestType(request, RequestType.HEARTBEAT); } + @Override + protected boolean canHandleWithUILock() { + return true; + } + /** * Handles a heartbeat request for the given session. Reads the GET * parameter named {@link ApplicationConstants#UI_ID_PARAMETER} to identify @@ -61,7 +66,9 @@ protected boolean canHandleRequest(VaadinRequest request) { @Override public boolean synchronizedHandleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response) throws IOException { - UI ui = session.getService().findUI(request); + UI ui = session.isUILockingEnabled() + ? session.getService().findUI(session, request) + : session.getService().findUI(request); if (ui != null) { ui.getInternals() .setLastHeartbeatTimestamp(System.currentTimeMillis()); diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/PushHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/PushHandler.java index 7658f51d80c..e2a14577a84 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/PushHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/PushHandler.java @@ -358,9 +358,14 @@ void callWithUi(final AtmosphereResource resource, cleanDisconnectedUuidBuffer(resource); UI ui = null; - session.lock(); + // With UI locking, only the UI is locked, see VaadinSession + UI lockedUI = session.isUILockingEnabled() + ? service.findUI(session, vaadinRequest) + : null; + Runnable releaseLock = VaadinSession.lockForUI(session, lockedUI); try { - ui = service.findUI(vaadinRequest); + ui = session.isUILockingEnabled() ? lockedUI + : service.findUI(vaadinRequest); assert UI.getCurrent() == ui; if (ui == null) { @@ -397,7 +402,7 @@ void callWithUi(final AtmosphereResource resource, callErrorHandler(session, e); } finally { try { - session.unlock(); + releaseLock.run(); } catch (Exception e) { getLogger().warn("Error while unlocking session", e); // can't call ErrorHandler, we (hopefully) don't have a lock @@ -525,11 +530,16 @@ private VaadinSession handleConnectionLost(AtmosphereResourceEvent event) { } UI ui; - session.lock(); + // With UI locking, only the UI is locked, see VaadinSession + UI lockedUI = session.isUILockingEnabled() + ? findUIForDisconnect(service, session, vaadinRequest, resource) + : null; + Runnable releaseLock = VaadinSession.lockForUI(session, lockedUI); try { VaadinSession.setCurrent(session); // Sets UI.currentInstance - ui = service.findUI(vaadinRequest); + ui = session.isUILockingEnabled() ? lockedUI + : service.findUI(vaadinRequest); if (ui == null) { /* * UI not found, could be because FF has asynchronously closed @@ -600,7 +610,7 @@ private VaadinSession handleConnectionLost(AtmosphereResourceEvent event) { callErrorHandler(session, e); } finally { try { - session.unlock(); + releaseLock.run(); } catch (Exception e) { getLogger().warn("Error while unlocking session", e); // can't call ErrorHandler, we (hopefully) don't have a lock @@ -609,6 +619,22 @@ private VaadinSession handleConnectionLost(AtmosphereResourceEvent event) { return session; } + /** + * Finds the UI of a disconnect event without any lock, falling back to the + * UI using the given resource, see + * {@link #findUiUsingResource(AtmosphereResource, Collection)}. + */ + private static UI findUIForDisconnect(VaadinService service, + VaadinSession session, VaadinRequest request, + AtmosphereResource resource) { + UI ui = service.findUI(session, request); + if (ui == null) { + ui = findUiUsingResource(resource, session.getUIsWithoutLock()); + UI.setCurrent(ui); + } + return ui; + } + private static UI findUiUsingResource(AtmosphereResource resource, Collection uIs) { for (UI ui : uIs) { diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamReceiverHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamReceiverHandler.java index 84158914434..867c06d0ed8 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamReceiverHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamReceiverHandler.java @@ -194,11 +194,12 @@ protected void doHandleMultipartFileUpload(VaadinSession session, "IO Exception during file upload, fired as StreamingErrorEvent", exception); } catch (Exception exception) { - session.lock(); + Runnable releaseLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { session.getErrorHandler().error(new ErrorEvent(exception)); } finally { - session.unlock(); + releaseLock.run(); } } sendUploadResponse(response, success); @@ -338,7 +339,8 @@ protected boolean handleFileUploadValidationAndData(VaadinSession session, InputStream inputStream, StreamReceiver streamReceiver, String filename, String mimeType, long contentLength, StateNode node) throws UploadException { - session.lock(); + Runnable releaseLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { if (node == null) { throw new UploadException( @@ -349,7 +351,7 @@ protected boolean handleFileUploadValidationAndData(VaadinSession session, + node.getId() + " because the component was disabled"); } } finally { - session.unlock(); + releaseLock.run(); } try (InputStream handledStream = inputStream) { // Store ui reference so we can do cleanup even if node is @@ -366,11 +368,12 @@ protected boolean handleFileUploadValidationAndData(VaadinSession session, // close getLogger().debug("Exception closing inputStream", ioe); } catch (UploadException e) { - session.lock(); + Runnable releaseErrorLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { session.getErrorHandler().error(new ErrorEvent(e)); } finally { - session.unlock(); + releaseErrorLock.run(); } } return false; @@ -433,11 +436,12 @@ protected void sendUploadResponse(VaadinResponse response, boolean success) private void cleanStreamVariable(VaadinSession session, StreamReceiver streamReceiver) { - session.lock(); + Runnable releaseLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { session.getResourceRegistry().unregisterResource(streamReceiver); } finally { - session.unlock(); + releaseLock.run(); } } @@ -458,13 +462,14 @@ private final Pair streamToReceiver( boolean success = false; try { boolean listenProgress; - session.lock(); + Runnable releaseLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { streamVariable.streamingStarted(startedEvent); out = streamVariable.getOutputStream(); listenProgress = streamVariable.listenProgress(); } finally { - session.unlock(); + releaseLock.run(); } // Gets the output target stream @@ -503,11 +508,12 @@ private final Pair streamToReceiver( out.close(); StreamVariable.StreamingEndEvent event = new StreamingEndEventImpl( filename, type, totalBytes); - session.lock(); + Runnable releaseEndLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { streamVariable.streamingFinished(event); } finally { - session.unlock(); + releaseEndLock.run(); } success = true; } catch (UploadInterruptedException | IOException e) { @@ -534,12 +540,13 @@ private void onStreamingFailed(VaadinSession session, String filename, String type, long contentLength, StreamVariable streamVariable, OutputStream out, long totalBytes, final Exception exception) { tryToCloseStream(out); - session.lock(); + Runnable releaseLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { streamVariable.streamingFailed(new StreamingErrorEventImpl(filename, type, contentLength, totalBytes, exception)); } finally { - session.unlock(); + releaseLock.run(); } } @@ -552,11 +559,12 @@ private long updateProgress(VaadinSession session, // events are sent in intervals, or at the end of the file. if (lastStreamingEvent + getProgressEventInterval() <= now || bytesReadToBuffer <= 0) { - session.lock(); + Runnable releaseLock = VaadinSession.lockForUI(session, + UI.getCurrent()); try { streamVariable.onProgress(progressEvent); } finally { - session.unlock(); + releaseLock.run(); } return now; } diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamRequestHandler.java index be93d17cfed..381b2a8a80f 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/StreamRequestHandler.java @@ -30,6 +30,7 @@ import com.vaadin.flow.dom.DisabledUpdateMode; import com.vaadin.flow.dom.Element; import com.vaadin.flow.internal.StateNode; +import com.vaadin.flow.internal.StateTree; import com.vaadin.flow.internal.UrlUtil; import com.vaadin.flow.internal.streams.ActiveTransfer; import com.vaadin.flow.server.AbstractStreamResource; @@ -147,7 +148,9 @@ private void callElementResourceHandler(VaadinSession session, ActiveTransfer transfer = new ActiveTransfer(pathInfo, owner); Registration transferRegistration = null; - session.lock(); + // With UI locking, the owner's UI is locked instead of the session + Runnable releaseLock = VaadinSession.lockForUI(session, + getOwnerUI(node)); try { if (blockInert(elementRequest, node) || blockDisabled(elementRequest, node) || !node.isAttached() @@ -212,7 +215,7 @@ private void callElementResourceHandler(VaadinSession session, .registerActiveTransfer(transfer); } } finally { - session.unlock(); + releaseLock.run(); } try { elementRequest.getElementRequestHandler().handleRequest( @@ -226,6 +229,12 @@ private void callElementResourceHandler(VaadinSession session, } } + private static UI getOwnerUI(StateNode node) { + return node != null && node.getOwner() instanceof StateTree tree + ? tree.getUI() + : null; + } + private static boolean blockDisabled( StreamResourceRegistry.ElementStreamResource elementRequest, StateNode node) { diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlRequestHandler.java index 30cc378a11b..21dbfba8f7f 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlRequestHandler.java @@ -139,12 +139,19 @@ public boolean isReadAndWriteOutsideSessionLock() { return true; } + @Override + protected boolean canHandleWithUILock() { + return true; + } + @Override public Optional synchronizedHandleRequest( VaadinSession session, VaadinRequest request, VaadinResponse response, String requestBody) throws IOException, UnsupportedOperationException { - UI uI = session.getService().findUI(request); + UI uI = session.isUILockingEnabled() + ? session.getService().findUI(session, request) + : session.getService().findUI(request); if (uI == null) { // This should not happen but it will if the UI has been closed. We // really don't want to see it in the server logs though diff --git a/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlWriter.java b/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlWriter.java index c66d862cc4d..63d52c42c60 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlWriter.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/communication/UidlWriter.java @@ -133,7 +133,11 @@ public ObjectNode createUidl(UI ui, boolean async, boolean resync) { // Purge pending access calls as they might produce additional changes // to write out - service.runPendingAccessTasks(session); + if (session.isUILockingEnabled()) { + uiInternals.runPendingAccessTasks(); + } else { + service.runPendingAccessTasks(session); + } // Paints components getLogger().debug("* Creating response to client"); diff --git a/flow-server/src/main/java/com/vaadin/flow/server/streams/UploadEvent.java b/flow-server/src/main/java/com/vaadin/flow/server/streams/UploadEvent.java index 089a25af190..500dd432379 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/streams/UploadEvent.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/streams/UploadEvent.java @@ -204,6 +204,10 @@ public UI getUI() { } private UI getUiFromSession(Component value) { + if (session.isUILockingEnabled()) { + return session.findUIWithoutLock(Integer + .parseInt((String) ComponentUtil.getData(value, "uiid"))); + } try { session.lock(); return session.getUIById(Integer diff --git a/flow-server/src/main/java/com/vaadin/flow/signals/local/ValueSignal.java b/flow-server/src/main/java/com/vaadin/flow/signals/local/ValueSignal.java index 23689cff69a..f85462bb5e3 100644 --- a/flow-server/src/main/java/com/vaadin/flow/signals/local/ValueSignal.java +++ b/flow-server/src/main/java/com/vaadin/flow/signals/local/ValueSignal.java @@ -110,7 +110,7 @@ protected void checkPreconditions() { // Track if the signal has ever been accessed without a locked session VaadinSession session = VaadinSession.getCurrent(); - if (session == null || !session.hasLock()) { + if (session == null || !(session.hasLock() || session.hasAccess())) { usedWithoutSessionLock = true; } diff --git a/flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java b/flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java new file mode 100644 index 00000000000..f30516d5995 --- /dev/null +++ b/flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java @@ -0,0 +1,324 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.server; + +import java.util.Locale; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.vaadin.flow.component.UI; +import com.vaadin.flow.internal.CurrentInstance; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class UILockingTest { + + private static final long TIMEOUT_SECONDS = 5; + + private MockVaadinSession session; + private UI ui1; + private UI ui2; + + @BeforeEach + void setUp() { + session = new MockVaadinSession(new MockVaadinServletService()); + session.applyLockStrategy(SessionLockCheckStrategy.THROW); + session.applyUILocking(true); + ui1 = addUI(0); + ui2 = addUI(1); + } + + @AfterEach + void tearDown() { + CurrentInstance.clearAll(); + } + + @Test + void accessSynchronously_holdsOnlyUILock() { + AtomicBoolean ran = new AtomicBoolean(); + ui1.accessSynchronously(() -> { + assertTrue(ui1.getInternals().hasUILock()); + assertFalse(session.hasLock()); + assertFalse(ui2.getInternals().hasUILock()); + assertSame(ui1, UI.getCurrent()); + ui1.getElement().setAttribute("foo", "bar"); + ran.set(true); + }); + assertTrue(ran.get()); + assertFalse(ui1.getInternals().hasUILock()); + } + + @Test + void uiStateWithSessionLockOnly_throws() { + session.lock(); + try { + assertThrows(IllegalStateException.class, + () -> ui1.getElement().setAttribute("foo", "bar")); + } finally { + session.unlock(); + } + } + + @Test + void sessionStateAccessibleWithUILock() { + ui1.accessSynchronously(() -> { + assertTrue(session.hasAccess()); + session.setAttribute("foo", "bar"); + assertEquals("bar", session.getAttribute("foo")); + assertEquals(2, session.getUIs().size()); + }); + assertFalse(session.hasAccess()); + } + + @Test + void busyUI_doesNotBlockOtherUIOrSession() throws Exception { + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = holdUI(ui1, locked, release); + try { + assertTrue(locked.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + // Neither the other UI nor the session is blocked + AtomicBoolean ran = new AtomicBoolean(); + ui2.accessSynchronously(() -> ran.set(true)); + assertTrue(ran.get()); + + assertTrue(session.getLockInstance().tryLock(TIMEOUT_SECONDS, + TimeUnit.SECONDS)); + session.getLockInstance().unlock(); + } finally { + release.countDown(); + holder.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + } + } + + @Test + void access_busyUI_runsWhenUIIsReleased() throws Exception { + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = holdUI(ui1, locked, release); + Future future; + AtomicReference taskThread = new AtomicReference<>(); + try { + assertTrue(locked.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + + future = ui1.access(() -> { + assertTrue(ui1.getInternals().hasUILock()); + taskThread.set(Thread.currentThread()); + }); + assertFalse(future.isDone()); + } finally { + release.countDown(); + holder.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + } + future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + // Run by the thread that released the UI lock + assertSame(holder, taskThread.get()); + } + + @Test + void access_freeUI_runsImmediately() throws Exception { + Future future = ui1.access( + () -> assertTrue(ui1.getInternals().hasUILock())); + future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertTrue(future.isDone()); + assertFalse(ui1.getInternals().hasUILock()); + } + + @Test + void accessSynchronously_busyUIWhileHoldingSessionLock_throws() + throws Exception { + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = holdUI(ui1, locked, release); + try { + assertTrue(locked.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + session.lock(); + try { + // Waiting here could deadlock, so it is refused + assertThrows(IllegalStateException.class, + () -> ui1.accessSynchronously(() -> { + })); + } finally { + session.unlock(); + } + } finally { + release.countDown(); + holder.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + } + } + + @Test + void accessSynchronously_freeUIWhileHoldingOtherUILock_runs() { + AtomicBoolean ran = new AtomicBoolean(); + ui1.accessSynchronously(() -> ui2.accessSynchronously(() -> { + assertTrue(ui1.getInternals().hasUILock()); + assertTrue(ui2.getInternals().hasUILock()); + ran.set(true); + })); + assertTrue(ran.get()); + } + + @Test + void uiThreadMayLockSession() { + AtomicBoolean ran = new AtomicBoolean(); + ui1.accessSynchronously(() -> { + session.lock(); + try { + assertTrue(session.hasLock()); + ran.set(true); + } finally { + session.unlock(); + } + }); + assertTrue(ran.get()); + } + + @Test + void setLocale_busyUIIsUpdatedWhenReleased() throws Exception { + Locale locale = Locale.GERMAN.equals(ui1.getLocale()) ? Locale.FRENCH + : Locale.GERMAN; + CountDownLatch locked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = holdUI(ui1, locked, release); + try { + assertTrue(locked.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + session.lock(); + try { + session.setLocale(locale); + } finally { + session.unlock(); + } + // The free UI is updated right away, the busy one later + assertEquals(locale, ui2.getLocale()); + assertNotEquals(locale, ui1.getLocale()); + } finally { + release.countDown(); + holder.join(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + } + assertEquals(locale, ui1.getLocale()); + } + + @Test + void findUIWithoutLock_returnsUIOfSession() { + assertSame(ui1, session.findUIWithoutLock(ui1.getUIId())); + assertSame(ui2, session.findUIWithoutLock(ui2.getUIId())); + assertEquals(2, session.getUIsWithoutLock().size()); + } + + @Test + void lockForUI_locksOnlyTheUI() { + Runnable release = VaadinSession.lockForUI(session, ui1); + try { + assertTrue(ui1.getInternals().hasUILock()); + assertFalse(session.hasLock()); + } finally { + release.run(); + } + assertFalse(ui1.getInternals().hasUILock()); + + release = VaadinSession.lockForUI(session, null); + try { + assertTrue(session.hasLock()); + } finally { + release.run(); + } + } + + @Test + void sessionLocking_uiLockNotUsed() { + MockVaadinSession sessionLocked = new MockVaadinSession( + new MockVaadinServletService()); + assertFalse(sessionLocked.isUILockingEnabled()); + + UI ui = new TestUI(0); + sessionLocked.lock(); + try { + ui.getInternals().setSession(sessionLocked); + sessionLocked.addUI(ui); + } finally { + sessionLocked.unlock(); + } + + ui.accessSynchronously(() -> { + assertTrue(sessionLocked.hasLock()); + assertFalse(ui.getInternals().hasUILock()); + }); + } + + /** + * Adds a UI the same way bootstrap does: with the session lock and the lock + * of the new UI held. + */ + private UI addUI(int id) { + UI ui = new TestUI(id); + session.lock(); + try { + assertTrue(ui.getInternals().tryLockUI()); + try { + ui.getInternals().setSession(session); + session.addUI(ui); + } finally { + ui.getInternals().unlockUI(); + } + } finally { + session.unlock(); + } + return ui; + } + + /** + * Starts a thread that holds the lock of the given UI until released. + */ + private static Thread holdUI(UI ui, CountDownLatch locked, + CountDownLatch release) { + Thread thread = new Thread(() -> ui.accessSynchronously(() -> { + locked.countDown(); + try { + release.await(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + })); + thread.start(); + return thread; + } + + private static class TestUI extends UI { + private final int id; + + private TestUI(int id) { + this.id = id; + } + + @Override + public int getUIId() { + return id; + } + } +} diff --git a/vaadin-cdi/src/main/java/com/vaadin/cdi/context/VaadinSessionScopedContext.java b/vaadin-cdi/src/main/java/com/vaadin/cdi/context/VaadinSessionScopedContext.java index dfbec5b72b2..e84ab5770da 100644 --- a/vaadin-cdi/src/main/java/com/vaadin/cdi/context/VaadinSessionScopedContext.java +++ b/vaadin-cdi/src/main/java/com/vaadin/cdi/context/VaadinSessionScopedContext.java @@ -141,14 +141,16 @@ public ContextualStorageManager() { /** * Checks whether the context is active, i.e. there is a current session - * and it is locked by the current thread. + * and it is locked by the current thread, or with UI locking the lock + * of one of its UIs is held, see {@link VaadinSession#hasAccess()}. * * @return {@code true} if the context is active, {@code false} * otherwise */ protected boolean isActive() { VaadinSession session = VaadinSession.getCurrent(); - return session != null && session.hasLock(); + return session != null + && (session.hasLock() || session.hasAccess()); } /** @@ -167,11 +169,35 @@ protected ContextualStorage getContextualStorage( Contextual contextual, boolean createIfNotExist) { VaadinSession session = VaadinSession.getCurrentOrThrow(); ContextualStorage storage = findContextualStorage(session); - if (storage == null && createIfNotExist) { + if (storage != null || !createIfNotExist) { + return storage; + } + if (!session.isUILockingEnabled()) { storage = new ContextualStorage(beanManager, false, true); session.setAttribute(ATTRIBUTE_NAME, storage); + return storage; + } + /* + * With UI locking, UIs of the session access the storage + * concurrently, and it must be created only once. Waiting for the + * session lock from a UI thread is allowed. + */ + boolean lock = !session.hasLock(); + if (lock) { + session.getLockInstance().lock(); + } + try { + storage = findContextualStorage(session); + if (storage == null) { + storage = new ContextualStorage(beanManager, true, true); + session.setAttribute(ATTRIBUTE_NAME, storage); + } + return storage; + } finally { + if (lock) { + session.getLockInstance().unlock(); + } } - return storage; } private static ContextualStorage findContextualStorage( diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/SessionLockSupport.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/SessionLockSupport.java new file mode 100644 index 00000000000..7874495b293 --- /dev/null +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/SessionLockSupport.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.spring.scopes; + +import com.vaadin.flow.server.VaadinSession; + +/** + * Runs scope bookkeeping with the session lock held. + *

+ * With {@link VaadinSession#isUILockingEnabled() UI locking}, UI events such as + * detach are fired while holding only the UI lock, but the bean stores of a + * session are shared by all of its UIs. Acquiring the session lock from a UI + * thread is allowed since threads holding the session lock never wait for a UI + * lock. + *

+ * For internal use only. + */ +final class SessionLockSupport { + + private SessionLockSupport() { + // utility class + } + + /** + * Runs the task with the session lock held, acquiring it if the current + * thread does not hold it yet. + * + * @param session + * the session to lock, not {@code null} + * @param task + * the task to run, not {@code null} + */ + static void runLocked(VaadinSession session, Runnable task) { + if (session.hasLock()) { + task.run(); + return; + } + session.getLockInstance().lock(); + try { + task.run(); + } finally { + session.getLockInstance().unlock(); + } + } +} diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinRouteScope.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinRouteScope.java index 0ce57d6f482..57901fe3cb7 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinRouteScope.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinRouteScope.java @@ -100,7 +100,11 @@ private RouteBeanStore getBeanStore(UI ui) { } private void relocateStore(UI ui, String key) { - assert session.hasLock(); + SessionLockSupport.runLocked(session, + () -> doRelocateStore(ui, key)); + } + + private void doRelocateStore(UI ui, String key) { RouteBeanStore beanStore = routeStores.remove(key); if (beanStore == null) { LoggerFactory.getLogger(RouteStoreWrapper.class).trace( @@ -304,14 +308,15 @@ private RouteBeanStore(UI ui, VaadinSession session, @Override public void onComponentEvent(DetachEvent event) { - assert getVaadinSession().hasLock(); - uiDetachRegistration.remove(); - if (resetUI(event.getUI())) { - uiDetachRegistration = currentUI.addDetachListener(this); - } else { - destroy(); - detachUiCallback.accept(currentUI); - } + SessionLockSupport.runLocked(getVaadinSession(), () -> { + uiDetachRegistration.remove(); + if (resetUI(event.getUI())) { + uiDetachRegistration = currentUI.addDetachListener(this); + } else { + destroy(); + detachUiCallback.accept(currentUI); + } + }); } @Override diff --git a/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinUIScope.java b/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinUIScope.java index 38761f16bec..83a4aa9f3b1 100644 --- a/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinUIScope.java +++ b/vaadin-spring/src/main/java/com/vaadin/flow/spring/scopes/VaadinUIScope.java @@ -66,14 +66,15 @@ private UIStoreWrapper(VaadinSession session) { @Override public void onComponentEvent(DetachEvent event) { - assert session.hasLock(); - UI ui = event.getUI(); - if (ui.isClosing()) { - BeanStore beanStore = uiStores.remove(ui.getUIId()); - if (beanStore != null) { - beanStore.destroy(); + SessionLockSupport.runLocked(session, () -> { + UI ui = event.getUI(); + if (ui.isClosing()) { + BeanStore beanStore = uiStores.remove(ui.getUIId()); + if (beanStore != null) { + beanStore.destroy(); + } } - } + }); } BeanStore getBeanStore(UI ui) { From 03f06e246b262704a55425b67b51baacde9da96e Mon Sep 17 00:00:00 2001 From: OriginalFelix Date: Wed, 28 Oct 2026 14:32:51 +0100 Subject: [PATCH 4/8] test: verify requests for a UI are answered while another UI is locked --- .../communication/UILockingRequestTest.java | 321 ++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java new file mode 100644 index 00000000000..f27116c1c96 --- /dev/null +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java @@ -0,0 +1,321 @@ +/* + * Copyright 2000-2026 Vaadin Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.vaadin.flow.server.communication; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.BooleanSupplier; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.vaadin.flow.component.UI; +import com.vaadin.flow.internal.CurrentInstance; +import com.vaadin.flow.server.MockVaadinServletService; +import com.vaadin.flow.server.MockVaadinSession; +import com.vaadin.flow.server.SessionLockCheckStrategy; +import com.vaadin.flow.server.VaadinRequest; +import com.vaadin.flow.server.VaadinResponse; +import com.vaadin.flow.server.VaadinSession; +import com.vaadin.flow.shared.ApplicationConstants; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Sends real heartbeat and UIDL requests through the request handlers while + * another thread keeps the lock of a different UI of the same session. + */ +class UILockingRequestTest { + + private static final long TIMEOUT_SECONDS = 5; + + private final ExecutorService executor = Executors.newCachedThreadPool(); + + private MockVaadinServletService service; + private VaadinSession session; + private UI ui1; + private UI ui2; + + private final CountDownLatch ui1Locked = new CountDownLatch(1); + private final CountDownLatch releaseUI1 = new CountDownLatch(1); + private Future ui1Holder; + + @BeforeEach + void setUp() { + service = new MockVaadinServletService(); + session = new MockVaadinSession(service) { + { + applyLockStrategy(SessionLockCheckStrategy.THROW); + applyUILocking(true); + } + }; + ui1 = addUI(1); + ui2 = addUI(2); + } + + @AfterEach + void tearDown() throws Exception { + releaseUI1.countDown(); + if (ui1Holder != null) { + ui1Holder.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } + executor.shutdownNow(); + CurrentInstance.clearAll(); + } + + @Test + void heartbeatForOtherUI_answeredWhileUIIsLocked() throws Exception { + ui2.accessSynchronously( + () -> ui2.getInternals().setLastHeartbeatTimestamp(0)); + holdUI1(); + VaadinResponse response = mock(VaadinResponse.class); + + boolean handled = handleInOtherThread(() -> new HeartbeatHandler() + .handleRequest(session, request("heartbeat", ui2), response)); + + assertTrue(handled); + verify(response).setHeader("Cache-Control", "no-cache"); + assertTrue(ui2.getInternals().getLastHeartbeatTimestamp() > 0); + assertUI1StillLocked(); + } + + @Test + void uidlForOtherUI_handledWithOnlyItsOwnLockWhileUIIsLocked() + throws Exception { + holdUI1(); + AtomicReference rpcUI = new AtomicReference<>(); + AtomicBoolean ownLockHeld = new AtomicBoolean(); + AtomicBoolean sessionLockHeld = new AtomicBoolean(true); + AtomicReference attribute = new AtomicReference<>(); + UidlRequestHandler handler = createUidlHandler((ui, body) -> { + rpcUI.set(ui); + ownLockHeld.set(ui.getInternals().hasUILock()); + sessionLockHeld.set(session.hasLock()); + // Session state stays usable while holding only the UI lock + session.setAttribute("handled-by", ui.getUIId()); + attribute.set(session.getAttribute("handled-by")); + }); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + + boolean handled = handleInOtherThread(() -> handler.handleRequest( + session, request("uidl", ui2), response(output))); + + assertTrue(handled); + assertSame(ui2, rpcUI.get()); + assertTrue(ownLockHeld.get(), "UI2 must be locked during the RPC"); + assertFalse(sessionLockHeld.get(), + "The session must not be locked during the RPC"); + assertEquals(2, attribute.get()); + assertEquals("{\"ui\":2}", output.toString(StandardCharsets.UTF_8)); + assertUI1StillLocked(); + } + + @Test + void repeatedRequestsForOtherUI_allAnsweredWhileUIStaysLocked() + throws Exception { + holdUI1(); + UidlRequestHandler handler = createUidlHandler((ui, body) -> { + }); + + for (int i = 0; i < 10; i++) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + assertTrue(handleInOtherThread(() -> handler.handleRequest(session, + request("uidl", ui2), response(output)))); + assertEquals("{\"ui\":2}", output.toString(StandardCharsets.UTF_8)); + assertTrue(handleInOtherThread(() -> new HeartbeatHandler() + .handleRequest(session, request("heartbeat", ui2), + mock(VaadinResponse.class)))); + } + assertUI1StillLocked(); + } + + @Test + void uidlForLockedUI_waitsUntilUIIsReleased() throws Exception { + holdUI1(); + AtomicReference rpcUI = new AtomicReference<>(); + UidlRequestHandler handler = createUidlHandler( + (ui, body) -> rpcUI.set(ui)); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + + Future ui1Request = executor.submit(() -> handler + .handleRequest(session, request("uidl", ui1), + response(output))); + + // The request waits for the UI lock, not for the session lock + waitUntil(() -> ui1.getInternals().getUILock().hasQueuedThreads()); + assertFalse(ui1Request.isDone()); + assertFalse(((ReentrantLock) session.getLockInstance()).isLocked()); + + // Meanwhile the other UI keeps answering + assertTrue(handleInOtherThread(() -> new HeartbeatHandler() + .handleRequest(session, request("heartbeat", ui2), + mock(VaadinResponse.class)))); + + releaseUI1.countDown(); + assertTrue(ui1Request.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertSame(ui1, rpcUI.get()); + assertEquals("{\"ui\":1}", output.toString(StandardCharsets.UTF_8)); + } + + /** + * Starts a thread that holds the lock of UI1 until the test ends. + */ + private void holdUI1() throws InterruptedException { + ui1Holder = executor.submit(() -> ui1.accessSynchronously(() -> { + ui1Locked.countDown(); + try { + releaseUI1.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + })); + assertTrue(ui1Locked.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + } + + private void assertUI1StillLocked() { + assertTrue(ui1.getInternals().getUILock().isLocked()); + assertFalse(ui1Holder.isDone()); + } + + /** + * Runs the request in another thread, failing instead of hanging if it is + * blocked. + */ + private boolean handleInOtherThread(Callable request) + throws Exception { + Future result = executor.submit(request); + try { + return result.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (TimeoutException e) { + result.cancel(true); + fail("The request was blocked although its UI is not locked"); + return false; + } + } + + private interface RpcCallback { + void handleRpc(UI ui, String body); + } + + private static UidlRequestHandler createUidlHandler(RpcCallback rpc) { + ServerRpcHandler rpcHandler = new ServerRpcHandler() { + @Override + public void handleRpc(UI ui, String requestBody, + VaadinRequest request) { + rpc.handleRpc(ui, requestBody); + } + }; + return new UidlRequestHandler() { + @Override + protected ServerRpcHandler createRpcHandler() { + return rpcHandler; + } + + @Override + void writeUidl(UI ui, Writer writer, boolean resync) + throws IOException { + writer.write("{\"ui\":" + ui.getUIId() + "}"); + } + }; + } + + private VaadinRequest request(String type, UI ui) throws IOException { + VaadinRequest request = mock(VaadinRequest.class); + when(request.getService()).thenReturn(service); + when(request.getParameter(ApplicationConstants.REQUEST_TYPE_PARAMETER)) + .thenReturn(type); + when(request.getParameter(ApplicationConstants.UI_ID_PARAMETER)) + .thenReturn(String.valueOf(ui.getUIId())); + when(request.getReader()) + .thenReturn(new BufferedReader(new StringReader("{}"))); + return request; + } + + private static VaadinResponse response(ByteArrayOutputStream output) + throws IOException { + VaadinResponse response = mock(VaadinResponse.class); + when(response.getOutputStream()).thenReturn(output); + return response; + } + + /** + * Adds a UI the same way bootstrap does: with the session lock and the lock + * of the new UI held. + */ + private UI addUI(int id) { + UI ui = new TestUI(id); + session.lock(); + try { + assertTrue(ui.getInternals().tryLockUI()); + try { + ui.getInternals().setSession(session); + session.addUI(ui); + } finally { + ui.getInternals().unlockUI(); + } + } finally { + session.unlock(); + } + return ui; + } + + private static void waitUntil(BooleanSupplier condition) + throws InterruptedException { + long deadline = System.nanoTime() + + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS); + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + fail("Condition not met within " + TIMEOUT_SECONDS + "s"); + } + Thread.sleep(10); + } + } + + private static class TestUI extends UI { + private final int id; + + private TestUI(int id) { + this.id = id; + } + + @Override + public int getUIId() { + return id; + } + } +} From e8dbd283238323e18dd4c4d6d7ef2415295d5cfe Mon Sep 17 00:00:00 2001 From: OriginalFelix Date: Wed, 28 Oct 2026 15:36:38 +0100 Subject: [PATCH 5/8] test: verify uiLocking parameter enables UI locking for new sessions --- .../DefaultDeploymentConfigurationTest.java | 17 +++++ .../vaadin/flow/server/VaadinServiceTest.java | 68 +++++++++++++++++++ 2 files changed, 85 insertions(+) diff --git a/flow-server/src/test/java/com/vaadin/flow/server/DefaultDeploymentConfigurationTest.java b/flow-server/src/test/java/com/vaadin/flow/server/DefaultDeploymentConfigurationTest.java index 4fb5a18c751..f908c1b7ead 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/DefaultDeploymentConfigurationTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/DefaultDeploymentConfigurationTest.java @@ -344,6 +344,23 @@ void checkLockStrategy_unrecognizedValue_fallsBackToAssert() { config.getSessionLockCheckStrategy()); } + @Test + void uiLocking_disabledByDefault() { + DefaultDeploymentConfiguration config = createDeploymentConfig( + new Properties()); + + assertFalse(config.isUILockingEnabled()); + } + + @Test + void uiLocking_enabledViaInitParameter() { + Properties init = new Properties(); + init.put(InitParameters.SERVLET_PARAMETER_UI_LOCKING, "true"); + DefaultDeploymentConfiguration config = createDeploymentConfig(init); + + assertTrue(config.isUILockingEnabled()); + } + @Test void pushMode_unrecognizedValue_fallsBackToDisabled() { Properties init = new Properties(); diff --git a/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java b/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java index 5276e9054f9..07142558b22 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java @@ -17,6 +17,8 @@ import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.HttpSessionBindingEvent; import java.util.ArrayList; @@ -36,6 +38,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @@ -73,6 +76,7 @@ import com.vaadin.flow.server.communication.WebComponentProvider; import com.vaadin.flow.server.menu.AvailableViewInfo; import com.vaadin.flow.server.startup.ApplicationRouteRegistry; +import com.vaadin.flow.shared.ApplicationConstants; import com.vaadin.flow.theme.Theme; import com.vaadin.tests.util.MockDeploymentConfiguration; @@ -1195,4 +1199,68 @@ private InstantiatorFactory createInstantiatorFactory() { private static MockVaadinServletService createService() { return new MockVaadinServletService(); } + + @Test + void createSession_uiLockingEnabled_sessionUsesUILocking() + throws Exception { + MockDeploymentConfiguration config = new MockDeploymentConfiguration(); + config.setApplicationOrSystemProperty( + InitParameters.SERVLET_PARAMETER_UI_LOCKING, "true"); + + VaadinSession session = createSessionForNewRequest( + new MockVaadinServletService(config)); + + assertTrue(session.isUILockingEnabled()); + } + + @Test + void createSession_uiLockingNotConfigured_sessionUsesSessionLock() + throws Exception { + VaadinSession session = createSessionForNewRequest( + new MockVaadinServletService( + new MockDeploymentConfiguration())); + + assertFalse(session.isUILockingEnabled()); + } + + /** + * Creates a session the way the first request of a user does, through + * {@link VaadinService#findVaadinSession(VaadinRequest)}. + */ + private static VaadinSession createSessionForNewRequest( + VaadinService service) throws Exception { + ReentrantLock lock = new ReentrantLock(); + WrappedSession wrappedSession = new WrappedHttpSession( + mock(HttpSession.class)) { + @Override + public Object getAttribute(String name) { + if ((service.getServiceName() + ".lock").equals(name)) { + return lock; + } + return super.getAttribute(name); + } + }; + VaadinRequest request = new VaadinServletRequest( + mock(HttpServletRequest.class), service) { + @Override + public String getParameter(String name) { + if (ApplicationConstants.REQUEST_TYPE_PARAMETER.equals(name)) { + return null; + } + return "1"; + } + + @Override + public WrappedSession getWrappedSession( + boolean allowSessionCreation) { + return wrappedSession; + } + }; + lock.lock(); + try { + return service.findVaadinSession(request); + } finally { + lock.unlock(); + } + } } From c127913a343a50832d3b641f23b2b1b470773318 Mon Sep 17 00:00:00 2001 From: OriginalFelix Date: Wed, 28 Oct 2026 16:17:16 +0100 Subject: [PATCH 6/8] test: pass servlet service to session creation helper --- .../src/test/java/com/vaadin/flow/server/VaadinServiceTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java b/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java index 07142558b22..44641869907 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/VaadinServiceTest.java @@ -1228,7 +1228,7 @@ void createSession_uiLockingNotConfigured_sessionUsesSessionLock() * {@link VaadinService#findVaadinSession(VaadinRequest)}. */ private static VaadinSession createSessionForNewRequest( - VaadinService service) throws Exception { + VaadinServletService service) throws Exception { ReentrantLock lock = new ReentrantLock(); WrappedSession wrappedSession = new WrappedHttpSession( mock(HttpSession.class)) { From 2022a02372bef6bf0aea9b3be529d64eca6b8903 Mon Sep 17 00:00:00 2001 From: OriginalFelix Date: Sun, 1 Nov 2026 10:57:09 +0100 Subject: [PATCH 7/8] chore: apply formatter --- .../flow/function/DeploymentConfiguration.java | 4 ++-- .../flow/server/SessionLockCheckStrategy.java | 12 ++++++------ .../flow/server/SynchronizedRequestHandler.java | 7 +++---- .../vaadin/flow/server/SessionUIServiceTest.java | 3 +-- .../com/vaadin/flow/server/UILockingTest.java | 4 ++-- .../communication/UILockingRequestTest.java | 16 +++++++++------- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java b/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java index b00fb3941ac..e04d577d9ea 100644 --- a/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java +++ b/flow-server/src/main/java/com/vaadin/flow/function/DeploymentConfiguration.java @@ -451,8 +451,8 @@ default boolean isReactEnabled() { * session lock is used */ default boolean isUILockingEnabled() { - return getBooleanProperty( - InitParameters.SERVLET_PARAMETER_UI_LOCKING, false); + return getBooleanProperty(InitParameters.SERVLET_PARAMETER_UI_LOCKING, + false); } /** diff --git a/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java b/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java index 672dc7863d3..ce10d301823 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/SessionLockCheckStrategy.java @@ -29,8 +29,8 @@ public enum SessionLockCheckStrategy { */ ASSERT { @Override - public void checkHasLock(BooleanSupplier hasLock, - VaadinSession session, String message) { + public void checkHasLock(BooleanSupplier hasLock, VaadinSession session, + String message) { assert hasLock.getAsBoolean() : message; } }, @@ -40,8 +40,8 @@ public void checkHasLock(BooleanSupplier hasLock, */ LOG { @Override - public void checkHasLock(BooleanSupplier hasLock, - VaadinSession session, String message) { + public void checkHasLock(BooleanSupplier hasLock, VaadinSession session, + String message) { if (!hasLock.getAsBoolean()) { session.getLogger().warn(message, new IllegalStateException(message)); @@ -54,8 +54,8 @@ public void checkHasLock(BooleanSupplier hasLock, */ THROW { @Override - public void checkHasLock(BooleanSupplier hasLock, - VaadinSession session, String message) { + public void checkHasLock(BooleanSupplier hasLock, VaadinSession session, + String message) { if (!hasLock.getAsBoolean()) { throw new IllegalStateException(message); } diff --git a/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java b/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java index 96a4ec05b2c..0eee5f3ff40 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/SynchronizedRequestHandler.java @@ -83,8 +83,8 @@ public boolean handleRequest(VaadinSession session, VaadinRequest request, session.lock(); Optional responseWriter; try { - responseWriter = synchronizedHandleRequest(session, - request, response, requestBody); + responseWriter = synchronizedHandleRequest(session, request, + response, requestBody); } finally { releaseUILocks(session); } @@ -114,8 +114,7 @@ public boolean handleRequest(VaadinSession session, VaadinRequest request, * with {@link VaadinSession#isUILockingEnabled() UI locking}. */ private boolean handleRequestWithUILock(VaadinSession session, UI ui, - VaadinRequest request, VaadinResponse response) - throws IOException { + VaadinRequest request, VaadinResponse response) throws IOException { UIInternals internals = ui.getInternals(); if (isReadAndWriteOutsideSessionLock()) { BufferedReader reader = request.getReader(); diff --git a/flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java b/flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java index b5b34a33b4c..3858af06b5e 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/SessionUIServiceTest.java @@ -91,8 +91,7 @@ void getUIs_unknownSession_emptyAndUnmodifiable() { List uis = service.getUIs(session); assertTrue(uis.isEmpty()); - assertThrows(UnsupportedOperationException.class, - () -> uis.add(ui(0))); + assertThrows(UnsupportedOperationException.class, () -> uis.add(ui(0))); } @Test diff --git a/flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java b/flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java index f30516d5995..c93723d4a10 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/UILockingTest.java @@ -143,8 +143,8 @@ void access_busyUI_runsWhenUIIsReleased() throws Exception { @Test void access_freeUI_runsImmediately() throws Exception { - Future future = ui1.access( - () -> assertTrue(ui1.getInternals().hasUILock())); + Future future = ui1 + .access(() -> assertTrue(ui1.getInternals().hasUILock())); future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); assertTrue(future.isDone()); assertFalse(ui1.getInternals().hasUILock()); diff --git a/flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java b/flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java index f27116c1c96..9820f96e43f 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/communication/UILockingRequestTest.java @@ -157,8 +157,9 @@ void repeatedRequestsForOtherUI_allAnsweredWhileUIStaysLocked() assertTrue(handleInOtherThread(() -> handler.handleRequest(session, request("uidl", ui2), response(output)))); assertEquals("{\"ui\":2}", output.toString(StandardCharsets.UTF_8)); - assertTrue(handleInOtherThread(() -> new HeartbeatHandler() - .handleRequest(session, request("heartbeat", ui2), + assertTrue(handleInOtherThread( + () -> new HeartbeatHandler().handleRequest(session, + request("heartbeat", ui2), mock(VaadinResponse.class)))); } assertUI1StillLocked(); @@ -172,9 +173,9 @@ void uidlForLockedUI_waitsUntilUIIsReleased() throws Exception { (ui, body) -> rpcUI.set(ui)); ByteArrayOutputStream output = new ByteArrayOutputStream(); - Future ui1Request = executor.submit(() -> handler - .handleRequest(session, request("uidl", ui1), - response(output))); + Future ui1Request = executor + .submit(() -> handler.handleRequest(session, + request("uidl", ui1), response(output))); // The request waits for the UI lock, not for the session lock waitUntil(() -> ui1.getInternals().getUILock().hasQueuedThreads()); @@ -182,8 +183,9 @@ void uidlForLockedUI_waitsUntilUIIsReleased() throws Exception { assertFalse(((ReentrantLock) session.getLockInstance()).isLocked()); // Meanwhile the other UI keeps answering - assertTrue(handleInOtherThread(() -> new HeartbeatHandler() - .handleRequest(session, request("heartbeat", ui2), + assertTrue(handleInOtherThread( + () -> new HeartbeatHandler().handleRequest(session, + request("heartbeat", ui2), mock(VaadinResponse.class)))); releaseUI1.countDown(); From bcd532bbc31d12c94c17c1581664bdf5e18804c8 Mon Sep 17 00:00:00 2001 From: mikhail Date: Tue, 1 Dec 2026 13:08:21 +0200 Subject: [PATCH 8/8] test: fix serialization and lock checks for UI locking Make SessionUIService serializable, as required for all Flow classes, and read the session state with the lock held in the session destroy test. --- .../main/java/com/vaadin/flow/server/SessionUIService.java | 3 ++- .../java/com/vaadin/flow/server/VaadinSessionTest.java | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java b/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java index 5fa69599ee1..bc9863efbd6 100644 --- a/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java +++ b/flow-server/src/main/java/com/vaadin/flow/server/SessionUIService.java @@ -15,6 +15,7 @@ */ package com.vaadin.flow.server; +import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -41,7 +42,7 @@ * One instance is owned by each {@link VaadinService}, see * {@link VaadinService#getSessionUIService()}. */ -public class SessionUIService { +public class SessionUIService implements Serializable { private final ConcurrentHashMap> uisBySession = new ConcurrentHashMap<>(); diff --git a/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java b/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java index 797a6d464b5..d232a4a1ba9 100644 --- a/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java +++ b/flow-server/src/test/java/com/vaadin/flow/server/VaadinSessionTest.java @@ -464,7 +464,12 @@ void fireSessionDestroy_sessionIsRemovedFromSessionUIService() { session.unlock(); mockService.fireSessionDestroy(session); - assertEquals(VaadinSessionState.CLOSED, session.getState()); + session.lock(); + try { + assertEquals(VaadinSessionState.CLOSED, session.getState()); + } finally { + session.unlock(); + } assertTrue(uiService.getUIs(session).isEmpty()); assertFalse(uiService.getSessions().contains(session)); }