You are viewing a plain text version of this content. The canonical link for it is here.
Posted to oak-commits@jackrabbit.apache.org by am...@apache.org on 2026/08/20 07:31:44 UTC
(jackrabbit-oak) branch trunk updated: OAK-12341 adding cache for service lookup (#3069)
This is an automated email from the ASF dual-hosted git repository.
Amoratinos pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/jackrabbit-oak.git
The following commit(s) were added to refs/heads/trunk by this push:
new 162ebd1f2d OAK-12341 adding cache for service lookup (#3069)
162ebd1f2d is described below
commit 162ebd1f2d0091098a67fb64492a0c274f1941ac
Author: Patrique Legault <pa...@gmail.com>
AuthorDate: Thu Aug 20 03:31:38 2026 -0400
OAK-12341 adding cache for service lookup (#3069)
* OAK-12341 adding cache for service lookup
* OAK-12341 Test to showcase blocking operation creating thread contention during high load
* OAK-12341 including test from e7ab1d6105fcff155ce0b88ef30d646dac649d69
* OAK-12341 adding additional test coverage
---------
Co-authored-by: patlego <pa...@gmail.com>
---
.../external/impl/principal/SyncConfigTracker.java | 29 ++-
.../SyncConfigTrackerConcurrencyTest.java | 226 +++++++++++++++++++++
.../impl/principal/SyncConfigTrackerTest.java | 16 ++
3 files changed, 267 insertions(+), 4 deletions(-)
diff --git a/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTracker.java b/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTracker.java
index e7564725e2..934e46f724 100644
--- a/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTracker.java
+++ b/oak-auth-external/src/main/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTracker.java
@@ -34,8 +34,10 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
/**
* {@code ServiceTracker} to detect any {@link SyncHandler} that has
@@ -46,12 +48,32 @@ final class SyncConfigTracker extends ServiceTracker {
private static final Logger log = LoggerFactory.getLogger(SyncConfigTracker.class);
private final SyncHandlerMappingTracker mappingTracker;
-
+
+ // maintained from addingService/removedService instead of calling getServiceReferences() on
+ // every read, which would otherwise contend on the shared ServiceTracker$Tracked monitor on
+ // every first PermissionProvider resolution for every session
+ private final List<ServiceReference> references = new CopyOnWriteArrayList<>();
+
SyncConfigTracker(@NotNull BundleContext context, @NotNull SyncHandlerMappingTracker mappingTracker) {
super(context, OsgiUtil.getFilter(SyncHandler.class, Collections.singletonMap(DefaultSyncConfigImpl.PARAM_USER_DYNAMIC_MEMBERSHIP, Boolean.TRUE.toString())), null);
this.mappingTracker = mappingTracker;
}
+ @Override
+ public Object addingService(ServiceReference reference) {
+ Object service = super.addingService(reference);
+ if (service != null) {
+ references.add(reference);
+ }
+ return service;
+ }
+
+ @Override
+ public void removedService(ServiceReference reference, Object service) {
+ references.remove(reference);
+ super.removedService(reference, service);
+ }
+
/**
* @return {@code true} if dynamic membership is enabled for at least one registered sync-handler; {@code false} otherwise.
*/
@@ -90,7 +112,7 @@ final class SyncConfigTracker extends ServiceTracker {
return Collections.emptySet();
}
- ServiceReference[] serviceReferences = getServiceReferences();
+ ServiceReference[] serviceReferences = getReferences();
Set<String> idpNames = new HashSet<>(serviceReferences.length);
for (ServiceReference ref : serviceReferences) {
if (PropertiesUtil.toBoolean(ref.getProperty(DefaultSyncConfigImpl.PARAM_GROUP_DYNAMIC_GROUPS), DefaultSyncConfigImpl.PARAM_GROUP_DYNAMIC_GROUPS_DEFAULT)) {
@@ -163,7 +185,6 @@ final class SyncConfigTracker extends ServiceTracker {
@NotNull
private ServiceReference[] getReferences() {
- ServiceReference[] refs = getServiceReferences();
- return (refs == null) ? new ServiceReference[0] : refs;
+ return references.toArray(new ServiceReference[0]);
}
}
diff --git a/oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTrackerConcurrencyTest.java b/oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTrackerConcurrencyTest.java
new file mode 100644
index 0000000000..206b76ed01
--- /dev/null
+++ b/oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTrackerConcurrencyTest.java
@@ -0,0 +1,226 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.jackrabbit.oak.spi.security.authentication.external.impl.principal;
+
+import org.apache.jackrabbit.api.security.user.UserManager;
+import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityProvider;
+import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncContext;
+import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncHandler;
+import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncedIdentity;
+import org.apache.sling.testing.mock.osgi.junit.OsgiContext;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.jcr.RepositoryException;
+import javax.jcr.ValueFactory;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
+import java.lang.management.ThreadMXBean;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+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.atomic.AtomicBoolean;
+import java.util.stream.Stream;
+
+import static org.apache.jackrabbit.oak.spi.security.authentication.external.impl.DefaultSyncConfigImpl.PARAM_NAME;
+import static org.apache.jackrabbit.oak.spi.security.authentication.external.impl.DefaultSyncConfigImpl.PARAM_USER_DYNAMIC_MEMBERSHIP;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+/**
+ * Reproduces the contention behind OAK-12341: many session threads resolving a
+ * {@code PermissionProvider} concurrently call {@code SyncConfigTracker.isEnabled()}. Before the
+ * fix, that call delegated to {@code ServiceTracker.getServiceReferences()} on every invocation,
+ * which internally synchronizes on the tracker's shared {@code Tracked} instance, so concurrent
+ * readers serialize on that monitor exactly as seen in the reported thread dump:
+ * <pre>
+ * "...": BLOCKED (on object monitor)
+ * at org.osgi.util.tracker.ServiceTracker.getServiceReferences(ServiceTracker.java:531)
+ * - waiting to lock <0x...> (a org.osgi.util.tracker.ServiceTracker$Tracked)
+ * at ...SyncConfigTracker.getReferences(SyncConfigTracker.java:166)
+ * </pre>
+ * The two tests below drive {@link #THREAD_COUNT} threads against the same {@code SyncConfigTracker}
+ * instance: one exercising the pre-fix code path (the raw, still publicly inherited
+ * {@code getServiceReferences()}), the other exercising {@code isEnabled()} as it exists after the
+ * OAK-12341 fix. Thread states are sampled via {@link ThreadMXBean} while both run.
+ */
+public class SyncConfigTrackerConcurrencyTest {
+
+ private static final Logger LOG = LoggerFactory.getLogger(SyncConfigTrackerConcurrencyTest.class);
+
+ private static final int THREAD_COUNT = Math.max(16, Runtime.getRuntime().availableProcessors() * 4);
+ private static final long SAMPLE_MILLIS = 50;
+ private static final int MATCHING_SYNC_HANDLER_COUNT = 5;
+
+ @Rule
+ public final OsgiContext context = new OsgiContext();
+
+ private SyncHandlerMappingTracker mappingTracker;
+ private SyncConfigTracker tracker;
+
+ @Before
+ public void before() {
+ mappingTracker = new SyncHandlerMappingTracker(context.bundleContext());
+ mappingTracker.open();
+
+ tracker = new SyncConfigTracker(context.bundleContext(), mappingTracker);
+ tracker.open();
+
+ // register several SyncHandlers with dynamic membership enabled, mirroring a deployment
+ // with multiple IDPs, so the ServiceTracker actually has more than one reference to
+ // fetch/copy on every getServiceReferences() call
+ SyncHandler syncHandlerInstance = new MockSyncHandler();
+ for (int i = 0; i < MATCHING_SYNC_HANDLER_COUNT; i++) {
+ context.registerService(SyncHandler.class, syncHandlerInstance,
+ Map.of(PARAM_NAME, "sh" + i, PARAM_USER_DYNAMIC_MEMBERSHIP, true));
+ }
+ // registered but never tracked: doesn't match the tracker's dynamic-membership filter
+ context.registerService(SyncHandler.class, syncHandlerInstance,
+ Map.of(PARAM_NAME, "sh-disabled", PARAM_USER_DYNAMIC_MEMBERSHIP, false));
+
+ assertTrue(tracker.isEnabled());
+ assertEquals(MATCHING_SYNC_HANDLER_COUNT, tracker.getServiceReferences().length);
+ }
+
+ @After
+ public void after() {
+ mappingTracker.close();
+ tracker.close();
+ }
+
+ /**
+ * Root-cause reproduction: hammering the inherited, un-cached
+ * {@code ServiceTracker.getServiceReferences()} from many threads reproduces the
+ * "BLOCKED ... a ServiceTracker$Tracked" contention from the OAK-12341 thread dump, even
+ * though every caller is only reading, not modifying, the tracked services.
+ */
+ @Test
+ public void concurrentGetServiceReferencesBlocksReaders() throws Exception {
+ long blockedMs = sampleForBlockingOnTrackedMonitor(tracker::getServiceReferences);
+ LOG.info("Contended threads were blocked for {}ms", blockedMs);
+ assertTrue("expected concurrent ServiceTracker.getServiceReferences() callers to contend on "
+ + "the shared Tracked monitor, as observed in the OAK-12341 thread dump", blockedMs > 0);
+ }
+
+ /**
+ * After the OAK-12341 fix, {@code isEnabled()} reads a {@code CopyOnWriteArrayList} that is
+ * maintained from {@code addingService}/{@code removedService} instead of calling
+ * {@code getServiceReferences()}, so concurrent readers never contend on the ServiceTracker's
+ * {@code Tracked} monitor.
+ */
+ @Test
+ public void concurrentIsEnabledDoesNotBlockReaders() throws Exception {
+ long blockedMs = sampleForBlockingOnTrackedMonitor(tracker::isEnabled);
+ LOG.info("Contended threads were blocked for {}ms", blockedMs);
+ assertEquals("expected isEnabled() to no longer contend on the ServiceTracker$Tracked monitor "
+ + "once service references are cached (OAK-12341)", 0, blockedMs);
+ }
+
+ /**
+ * Runs {@code action} directly on {@link #THREAD_COUNT} threads in a tight loop, so all of
+ * them contend on the tracker concurrently from the start rather than serializing through a
+ * single task submitter, and polls the {@link ThreadMXBean} of all worker threads in a batch
+ * for {@link #SAMPLE_MILLIS}, returning the accumulated blocked time observed on a
+ * {@code ServiceTracker$Tracked} monitor.
+ */
+ private long sampleForBlockingOnTrackedMonitor(Runnable action) throws Exception {
+ ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
+ assumeTrue("JVM supporting thread contention monitoring required",
+ threadMXBean.isThreadContentionMonitoringSupported());
+ threadMXBean.setThreadContentionMonitoringEnabled(true);
+
+ ExecutorService pool = Executors.newFixedThreadPool(THREAD_COUNT);
+ CountDownLatch allThreadsStarted = new CountDownLatch(THREAD_COUNT);
+ AtomicBoolean stop = new AtomicBoolean(false);
+ long[] threadIds = new long[THREAD_COUNT];
+ List<Future<?>> futures = new ArrayList<>();
+
+ try {
+ for (int i = 0; i < THREAD_COUNT; i++) {
+ int idx = i;
+ futures.add(pool.submit(() -> {
+ threadIds[idx] = Thread.currentThread().getId();
+ allThreadsStarted.countDown();
+ while (!stop.get()) {
+ action.run();
+ }
+ }));
+ }
+ assertTrue("worker threads did not start in time", allThreadsStarted.await(10, TimeUnit.SECONDS));
+
+ long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(SAMPLE_MILLIS);
+ long blockedMs = 0;
+ while (System.nanoTime() < deadline) {
+ ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(threadIds);
+ blockedMs += Stream.of(threadInfo)
+ .filter(Objects::nonNull)
+ .filter(info -> info.getThreadState() == Thread.State.BLOCKED)
+ .filter(info -> info.getLockName() != null && info.getLockName().contains("ServiceTracker$Tracked"))
+ .mapToLong(ThreadInfo::getBlockedTime)
+ .sum();
+ }
+ return blockedMs;
+ } finally {
+ stop.set(true);
+ for (Future<?> f : futures) {
+ f.get(10, TimeUnit.SECONDS);
+ }
+ pool.shutdown();
+ }
+ }
+
+ private static class MockSyncHandler implements SyncHandler {
+ @Override
+ public @NotNull String getName() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public @NotNull SyncContext createContext(@NotNull ExternalIdentityProvider idp, @NotNull UserManager userManager, @NotNull ValueFactory valueFactory) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public @Nullable SyncedIdentity findIdentity(@NotNull UserManager userManager, @NotNull String id) throws RepositoryException {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean requiresSync(@NotNull SyncedIdentity identity) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public @NotNull Iterator<SyncedIdentity> listIdentities(@NotNull UserManager userManager) throws RepositoryException {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTrackerTest.java b/oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTrackerTest.java
index b8a6b44d52..3acc6d2ef6 100644
--- a/oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTrackerTest.java
+++ b/oak-auth-external/src/test/java/org/apache/jackrabbit/oak/spi/security/authentication/external/impl/principal/SyncConfigTrackerTest.java
@@ -28,6 +28,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
+import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
@@ -44,6 +45,7 @@ import static org.apache.jackrabbit.oak.spi.security.authentication.external.imp
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -123,6 +125,20 @@ public class SyncConfigTrackerTest {
assertFalse(tracker.isEnabled());
}
+ @Test
+ public void testAddingServiceWithNullService() {
+ // the framework may return null from getService() (e.g. the service was
+ // concurrently unregistered before it could be resolved); the reference must
+ // not be tracked in that case
+ BundleContext bundleContext = mock(BundleContext.class);
+ ServiceReference reference = mock(ServiceReference.class);
+ when(bundleContext.getService(reference)).thenReturn(null);
+
+ SyncConfigTracker t = new SyncConfigTracker(bundleContext, mappingTracker);
+ assertNull(t.addingService(reference));
+ assertFalse(t.isEnabled());
+ }
+
@Test
public void testRemovedService() {
ServiceRegistration registration = context.bundleContext().registerService(SyncHandler.class.getName(), service, MapUtil.toDictionary(Collections.singletonMap(PARAM_USER_DYNAMIC_MEMBERSHIP, true)));