This is an automated email from the ASF dual-hosted git repository.

dakirily pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/qpid-broker-j.git


The following commit(s) were added to refs/heads/main by this push:
     new 63e4a5366d QPID-8753: [Broker-J] Make client registry timeout tests 
deterministic (#479)
63e4a5366d is described below

commit 63e4a5366dec349c009e25d7f5af50994cb79f1c
Author: Daniil Kirilyuk <[email protected]>
AuthorDate: Tue Nov 17 15:33:32 2026 +0100

    QPID-8753: [Broker-J] Make client registry timeout tests deterministic 
(#479)
---
 .../qpid/disttest/controller/ClientRegistry.java   |  34 +++-
 .../disttest/controller/ClientRegistryTest.java    | 223 +++++++++++++++------
 2 files changed, 195 insertions(+), 62 deletions(-)

diff --git 
a/perftests/src/main/java/org/apache/qpid/disttest/controller/ClientRegistry.java
 
b/perftests/src/main/java/org/apache/qpid/disttest/controller/ClientRegistry.java
index 9e479b104d..d8a6da33be 100644
--- 
a/perftests/src/main/java/org/apache/qpid/disttest/controller/ClientRegistry.java
+++ 
b/perftests/src/main/java/org/apache/qpid/disttest/controller/ClientRegistry.java
@@ -18,9 +18,9 @@
  */
 package org.apache.qpid.disttest.controller;
 
-
 import java.util.Collection;
 import java.util.Collections;
+import java.util.Objects;
 import java.util.Set;
 import java.util.concurrent.ConcurrentSkipListSet;
 
@@ -36,6 +36,18 @@ public class ClientRegistry
 
     private final Object _lock = new Object();
 
+    private final RegistrationWaiter _registrationWaiter;
+
+    public ClientRegistry()
+    {
+        this(Object::wait);
+    }
+
+    ClientRegistry(final RegistrationWaiter registrationWaiter)
+    {
+        _registrationWaiter = Objects.requireNonNull(registrationWaiter);
+    }
+
     public void registerClient(String clientName)
     {
         final boolean alreadyContainsClient = 
!_registeredClientNames.add(clientName);
@@ -66,18 +78,18 @@ public class ClientRegistry
      */
     public int awaitClients(final int numberOfClientsToAwait, final long 
idleTimeout)
     {
-        long startTime = System.currentTimeMillis();
+        final long startTime = currentTimeMillis();
         long deadlineForNextRegistration = deadline(idleTimeout);
 
         synchronized (_lock)
         {
             int numberOfClientsAbsent = numberAbsent(numberOfClientsToAwait);
 
-            while(numberOfClientsAbsent > 0 && System.currentTimeMillis() < 
deadlineForNextRegistration)
+            while(numberOfClientsAbsent > 0 && currentTimeMillis() < 
deadlineForNextRegistration)
             {
                 try
                 {
-                    _lock.wait(idleTimeout);
+                    _registrationWaiter.await(_lock, idleTimeout);
                 }
                 catch (InterruptedException e)
                 {
@@ -101,6 +113,10 @@ public class ClientRegistry
         }
     }
 
+    long currentTimeMillis()
+    {
+        return System.currentTimeMillis();
+    }
 
     private void logAwaitClients(int numberOfClientsToAwait, long idleTimeout, 
long startTime, int retVal)
     {
@@ -110,16 +126,22 @@ public class ClientRegistry
                         numberOfClientsToAwait,
                         idleTimeout,
                         retVal,
-                        System.currentTimeMillis() - startTime);
+                        currentTimeMillis() - startTime);
     }
 
     private long deadline(final long idleTimeout)
     {
-        return System.currentTimeMillis() + idleTimeout;
+        return currentTimeMillis() + idleTimeout;
     }
 
     private int numberAbsent(int numberOfClientsToAwait)
     {
         return numberOfClientsToAwait - _registeredClientNames.size();
     }
+
+    @FunctionalInterface
+    interface RegistrationWaiter
+    {
+        void await(final Object lock, final long idleTimeout) throws 
InterruptedException;
+    }
 }
diff --git 
a/perftests/src/test/java/org/apache/qpid/disttest/controller/ClientRegistryTest.java
 
b/perftests/src/test/java/org/apache/qpid/disttest/controller/ClientRegistryTest.java
index 1a8b5fe42a..352cbb14b6 100644
--- 
a/perftests/src/test/java/org/apache/qpid/disttest/controller/ClientRegistryTest.java
+++ 
b/perftests/src/test/java/org/apache/qpid/disttest/controller/ClientRegistryTest.java
@@ -19,31 +19,57 @@
 package org.apache.qpid.disttest.controller;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
-import java.util.Timer;
-import java.util.TimerTask;
-
-import org.apache.qpid.disttest.DistributedTestException;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.PriorityQueue;
+import java.util.Queue;
+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.AtomicReference;
 
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-public class ClientRegistryTest
+import org.apache.qpid.disttest.DistributedTestException;
+import org.apache.qpid.test.utils.UnitTestBase;
+
+public class ClientRegistryTest extends UnitTestBase
 {
     private static final String CLIENT1_REGISTERED_NAME = 
"CLIENT1_REGISTERED_NAME";
     private static final String CLIENT2_REGISTERED_NAME = 
"CLIENT2_REGISTERED_NAME";
     private static final String CLIENT3_REGISTERED_NAME = 
"CLIENT3_REGISTERED_NAME";
 
-    private long _awaitDelay = 100;
+    private static final long IDLE_TIMEOUT = 600;
+    private static final long REAL_IDLE_TIMEOUT = 1000;
+    private static final long REAL_TIMEOUT_TOLERANCE_MILLIS = 10;
+    private static final long TEST_TIMEOUT_SECONDS = 10;
 
+    private Queue<TimedEvent> _events;
+    private List<Long> _requestedWaits;
+    private long _currentTimeMillis;
     private ClientRegistry _clientRegistry;
 
     @BeforeEach
-    public void setUp() throws Exception
+    public void setUp()
     {
-        _clientRegistry = new ClientRegistry();
-        _awaitDelay = Long.getLong("ClientRegistryTest.awaitDelay", 100L);
+        _currentTimeMillis = 0;
+        _events = new 
PriorityQueue<>(Comparator.comparingLong(TimedEvent::timeMillis));
+        _requestedWaits = new ArrayList<>();
+        _clientRegistry = new ClientRegistry(this::waitForNextEvent)
+        {
+            @Override
+            long currentTimeMillis()
+            {
+                return _currentTimeMillis;
+            }
+        };
     }
 
     @Test
@@ -59,96 +85,181 @@ public class ClientRegistryTest
     public void testRejectsDuplicateClientNames()
     {
         _clientRegistry.registerClient(CLIENT1_REGISTERED_NAME);
+        assertThrows(DistributedTestException.class, () ->
+                _clientRegistry.registerClient(CLIENT1_REGISTERED_NAME));
+    }
+
+    @Test
+    public void testAwaitTimeoutWhenNoClientsRegister()
+    {
+        assertEquals(1, _clientRegistry.awaitClients(1, IDLE_TIMEOUT));
+        assertEquals(List.of(IDLE_TIMEOUT), _requestedWaits);
+        assertEquals(IDLE_TIMEOUT, _currentTimeMillis);
+    }
+
+    @Test
+    public void testAwaitOneClientWhenClientNotRegistered() throws Exception
+    {
+        final ClientRegistry clientRegistry = new ClientRegistry();
+        final ExecutorService executor = Executors.newSingleThreadExecutor();
         try
         {
-            _clientRegistry.registerClient(CLIENT1_REGISTERED_NAME);
-            fail("Should have thrown an exception");
+            final Future<Integer> result = executor.submit(() ->
+            {
+                final long start = System.nanoTime();
+                final int numberOfClientsAbsent = 
clientRegistry.awaitClients(1, REAL_IDLE_TIMEOUT);
+                final long elapsed = 
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
+                assertTrue(elapsed >= REAL_IDLE_TIMEOUT - 
REAL_TIMEOUT_TOLERANCE_MILLIS,
+                           "Registry returned before the timeout: " + elapsed);
+                return numberOfClientsAbsent;
+            });
+            assertEquals(1, result.get(TEST_TIMEOUT_SECONDS, 
TimeUnit.SECONDS).intValue());
         }
-        catch (final DistributedTestException e)
+        finally
         {
-            // pass
+            shutdownExecutor(executor);
         }
     }
 
-    @Test
-    public void testAwaitOneClientWhenClientNotRegistered()
-    {
-        int numberOfClientsAbsent = _clientRegistry.awaitClients(1, 
_awaitDelay);
-        assertEquals(1, numberOfClientsAbsent);
-    }
-
     @Test
     public void testAwaitOneClientWhenClientAlreadyRegistered()
     {
         _clientRegistry.registerClient(CLIENT1_REGISTERED_NAME);
 
-        int numberOfClientsAbsent = _clientRegistry.awaitClients(1, 
_awaitDelay);
+        final int numberOfClientsAbsent = _clientRegistry.awaitClients(1, 
IDLE_TIMEOUT);
         assertEquals(0, numberOfClientsAbsent);
+        assertTrue(_requestedWaits.isEmpty(), "Already registered clients must 
not wait");
     }
 
     @Test
-    public void testAwaitTwoClientsWhenClientRegistersWhilstWaiting()
+    public void testAwaitTwoClientsWhenClientRegistersWhilstWaiting() throws 
Exception
     {
-        _clientRegistry.registerClient(CLIENT1_REGISTERED_NAME);
-        registerClientLater(CLIENT2_REGISTERED_NAME, 50);
+        final CountDownLatch started = new CountDownLatch(1);
+        final AtomicReference<Thread> waiter = new AtomicReference<>();
+        final ClientRegistry clientRegistry = new ClientRegistry();
+        clientRegistry.registerClient(CLIENT1_REGISTERED_NAME);
 
-        int numberOfClientsAbsent = _clientRegistry.awaitClients(2, 
_awaitDelay);
-        assertEquals(0, numberOfClientsAbsent);
+        final ExecutorService executor = Executors.newFixedThreadPool(2);
+        try
+        {
+            final Future<Integer> result = executor.submit(() ->
+            {
+                waiter.set(Thread.currentThread());
+                started.countDown();
+                return clientRegistry.awaitClients(2, 
TimeUnit.MINUTES.toMillis(1));
+            });
+            assertTrue(started.await(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS), 
"Registry waiter did not start");
+            awaitTimedWait(waiter.get());
+            final Future<?> registration = executor.submit(() ->
+                    clientRegistry.registerClient(CLIENT2_REGISTERED_NAME));
+            registration.get(TEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
+
+            assertEquals(0, result.get(TEST_TIMEOUT_SECONDS, 
TimeUnit.SECONDS).intValue());
+        }
+        finally
+        {
+            shutdownExecutor(executor);
+        }
     }
 
     @Test
     public void testAwaitTimeoutForPromptRegistrations()
     {
-        registerClientsLaterAndAssertResult("Clients registering every 100ms 
should be within 600ms timeout",
-                new int[] {300, 400, 500},
-                600,
-                0);
+        registerClientAt(CLIENT1_REGISTERED_NAME, 300);
+        _events.add(new TimedEvent(700, () ->
+        {
+            // Wake without a registration.
+        }));
+        registerClientAt(CLIENT2_REGISTERED_NAME, 800);
+        _events.add(new TimedEvent(1000, () ->
+        {
+            // Force a deadline check after the second registration.
+        }));
+        registerClientAt(CLIENT3_REGISTERED_NAME, 1300);
+
+        assertEquals(0, _clientRegistry.awaitClients(3, IDLE_TIMEOUT));
+        assertEquals(1300, _currentTimeMillis, "Each registration must reset 
the idle timeout");
     }
 
     @Test
     public void testAwaitTimeoutForWhenThirdRegistrationIsLate()
     {
-        registerClientsLaterAndAssertResult("Third client registering tardily 
should exceed timeout",
-                new int[] {300, 400, 1500},
-                600,
-                1);
+        registerClientAt(CLIENT1_REGISTERED_NAME, 300);
+        registerClientAt(CLIENT2_REGISTERED_NAME, 400);
+        registerClientAt(CLIENT3_REGISTERED_NAME, 1500);
+
+        assertEquals(1, _clientRegistry.awaitClients(3, IDLE_TIMEOUT));
+        assertEquals(1000, _currentTimeMillis);
+        assertEquals(2, _clientRegistry.getClients().size());
     }
 
     @Test
     public void testAwaitTimeoutWhenSecondAndThirdRegistrationsAreLate()
     {
-        registerClientsLaterAndAssertResult("Second and third clients 
registering tardily should exceed timeout",
-                new int[] {300, 1500, 1500},
-                600,
-                2);
+        registerClientAt(CLIENT1_REGISTERED_NAME, 300);
+        registerClientAt(CLIENT2_REGISTERED_NAME, 1500);
+        registerClientAt(CLIENT3_REGISTERED_NAME, 1500);
+
+        assertEquals(2, _clientRegistry.awaitClients(3, IDLE_TIMEOUT));
+        assertEquals(900, _currentTimeMillis);
+        assertEquals(1, _clientRegistry.getClients().size());
     }
 
-    private void registerClientsLaterAndAssertResult(String message, int[] 
registrationDelays, int timeout, int expectedNumberOfAbsentees)
+    @Test
+    public void testAwaitTimeoutAfterSpuriousWakeups()
     {
-        registerClientLater(CLIENT1_REGISTERED_NAME, registrationDelays[0]);
-        registerClientLater(CLIENT2_REGISTERED_NAME, registrationDelays[1]);
-        registerClientLater(CLIENT3_REGISTERED_NAME, registrationDelays[2]);
+        _events.add(new TimedEvent(300, () ->
+        {
+            // Wake without a registration.
+        }));
+        _events.add(new TimedEvent(650, () ->
+        {
+            // Wake without a registration.
+        }));
+        registerClientAt(CLIENT1_REGISTERED_NAME, 700);
+
+        assertEquals(1, _clientRegistry.awaitClients(1, IDLE_TIMEOUT));
+        assertTrue(_currentTimeMillis >= IDLE_TIMEOUT, "An early wakeup must 
not end the wait");
+        assertTrue(_clientRegistry.getClients().isEmpty(), "The late client 
must remain unregistered");
+    }
 
-        int numberOfClientsAbsent = _clientRegistry.awaitClients(3, timeout);
+    private void waitForNextEvent(final Object lock, final long idleTimeout)
+    {
+        assertTrue(Thread.holdsLock(lock), "Registry must hold the monitor 
before waiting");
+        assertTrue(idleTimeout > 0, "Wait must have a positive timeout");
+        assertTrue(_currentTimeMillis < 10 * IDLE_TIMEOUT, "Registry exceeded 
the simulated time limit");
+        _requestedWaits.add(idleTimeout);
+        final long expiry = _currentTimeMillis + idleTimeout;
+        _currentTimeMillis = _events.isEmpty() ? expiry : Math.min(expiry, 
_events.peek().timeMillis());
+        while (!_events.isEmpty() && _events.peek().timeMillis() <= 
_currentTimeMillis)
+        {
+            _events.remove().action().run();
+        }
+    }
 
-        assertEquals(expectedNumberOfAbsentees, numberOfClientsAbsent, 
message);
+    private void registerClientAt(final String clientName, final long 
timeMillis)
+    {
+        _events.add(new TimedEvent(timeMillis, () -> 
_clientRegistry.registerClient(clientName)));
     }
 
-    private void registerClientLater(final String clientName, long 
delayInMillis)
+    private void awaitTimedWait(final Thread waiter) throws 
InterruptedException
     {
-        doLater(new TimerTask()
+        final long deadline = System.nanoTime() + 
TimeUnit.SECONDS.toNanos(TEST_TIMEOUT_SECONDS);
+        while (waiter.getState() != Thread.State.TIMED_WAITING)
         {
-            @Override
-            public void run()
-            {
-                _clientRegistry.registerClient(clientName);
-            }
-        }, delayInMillis);
+            assertTrue(System.nanoTime() < deadline, "Registry did not enter a 
timed wait");
+            TimeUnit.MILLISECONDS.sleep(1);
+        }
+    }
+
+    private void shutdownExecutor(final ExecutorService executor) throws 
InterruptedException
+    {
+        executor.shutdownNow();
+        assertTrue(executor.awaitTermination(TEST_TIMEOUT_SECONDS, 
TimeUnit.SECONDS),
+                "Registry workers did not terminate");
     }
 
-    private void doLater(TimerTask task, long delayInMillis)
+    private record TimedEvent(long timeMillis, Runnable action)
     {
-        Timer timer = new Timer();
-        timer.schedule(task, delayInMillis);
     }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to