예제 #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldReclaimAndRecreateWhenLullBetweenSpikesOccurs()
        internal virtual void ShouldReclaimAndRecreateWhenLullBetweenSpikesOccurs()
        {
            // given
            const int minSize = 50;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int BELOW_MIN_SIZE = MIN_SIZE / 5;
            int       belowMinSize = minSize / 5;
            const int maxSize      = 200;

            StatefulMonitor stateMonitor = new StatefulMonitor();
            FakeClock       clock        = new FakeClock();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LinkedQueuePool<Object> pool = getLinkedQueuePool(stateMonitor, clock, MIN_SIZE);
            LinkedQueuePool <object>          pool    = GetLinkedQueuePool(stateMonitor, clock, minSize);
            IList <FlyweightHolder <object> > holders = new LinkedList <FlyweightHolder <object> >();

            BuildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects(maxSize, clock, pool, holders);

            // when
            // After the peak, stay well below concurrent usage, using up all already present Flyweights in the process
            clock.Forward(110, TimeUnit.MILLISECONDS);
            // Requires some rounds to happen, since there is constant racing between releasing and acquiring which does
            // not always result in reaping of Flyweights, as there is reuse
            for (int i = 0; i < 30; i++)
            {
                // The latch is necessary to reduce races between batches
                foreach (FlyweightHolder holder in AcquireFromPool(pool, belowMinSize))
                {
                    holder.release();
                }
                clock.Forward(110, TimeUnit.MILLISECONDS);
            }

            // then
            // currentPeakSize should be at MIN_SIZE / 5
            assertTrue(stateMonitor.CurrentPeakSize.get() <= belowMinSize, "Expected " + stateMonitor.CurrentPeakSize.get() + " <= " + belowMinSize);
            // target size should remain at MIN_SIZE
            assertEquals(minSize, stateMonitor.TargetSize.get());
            // only the excess from the MAX_SIZE down to min size must have been disposed
            // +1 for the alarm from buildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects
            assertEquals(maxSize - minSize + 1, stateMonitor.DisposedConflict.get());

            stateMonitor.CreatedConflict.set(0);
            stateMonitor.DisposedConflict.set(0);

            // when
            // After the lull, recreate a peak
            ((IList <FlyweightHolder <object> >)holders).AddRange(AcquireFromPool(pool, maxSize));

            // then
            assertEquals(maxSize - minSize, stateMonitor.CreatedConflict.get());
            assertEquals(0, stateMonitor.DisposedConflict.get());
        }
예제 #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldMaintainPoolAtHighWatermarkWhenConcurrentUsagePassesMinSize()
        internal virtual void ShouldMaintainPoolAtHighWatermarkWhenConcurrentUsagePassesMinSize()
        {
            // given
            const int minSize = 50;
            const int maxSize = 200;
            const int midSize = 90;

            StatefulMonitor stateMonitor = new StatefulMonitor();
            FakeClock       clock        = new FakeClock();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LinkedQueuePool<Object> pool = getLinkedQueuePool(stateMonitor, clock, MIN_SIZE);
            LinkedQueuePool <object>          pool    = GetLinkedQueuePool(stateMonitor, clock, minSize);
            IList <FlyweightHolder <object> > holders = new LinkedList <FlyweightHolder <object> >();

            // when
            BuildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects(maxSize, clock, pool, holders);

            // then
            assertEquals(maxSize + 1, stateMonitor.CurrentPeakSize.get());                 // the peak method above does +1 on the peak

            // when

            /* After the peak, stay at MID_SIZE concurrent usage, using up all already present Flyweights in the process
             * but also keeping the high watermark above the MIN_SIZE
             * We must do this at least twice, since the counter for disposed is incremented once per release, if appropriate,
             * and only after the clock has ticked. Essentially this is one loop for reducing the watermark down to
             * mid size and one more loop to dispose of all excess resources. That does indeed mean that there is a lag
             * of one clock tick before resources are disposed. If this is a bug or not remains to be seen.
             */
            for (int i = 0; i < 2; i++)
            {
                clock.Forward(110, TimeUnit.MILLISECONDS);
                foreach (FlyweightHolder holder in AcquireFromPool(pool, midSize))
                {
                    holder.release();
                }
                clock.Forward(110, TimeUnit.MILLISECONDS);
                foreach (FlyweightHolder holder in AcquireFromPool(pool, midSize))
                {
                    holder.release();
                }
            }

            // then
            // currentPeakSize should be at MID_SIZE
            assertEquals(midSize, stateMonitor.CurrentPeakSize.get());
            // target size too
            assertEquals(midSize, stateMonitor.TargetSize.get());
            // only the excess from the MAX_SIZE down to mid size must have been disposed
            // +1 for the alarm from buildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects
            assertEquals(maxSize - midSize + 1, stateMonitor.DisposedConflict.get());
        }
예제 #3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldThrowThrottleExceptionWhenMaxDurationIsReached() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldThrowThrottleExceptionWhenMaxDurationIsReached()
        {
            // given
            TestThrottleLock  lockOverride = new TestThrottleLock();
            FakeClock         clock        = Clocks.fakeClock(1, TimeUnit.SECONDS);
            TransportThrottle throttle     = NewThrottleAndInstall(_channel, lockOverride, clock, Duration.ofSeconds(5));

            when(_channel.Writable).thenReturn(false);

            // when
            Future <Void> future = OtherThread.execute(state =>
            {
                throttle.Acquire(_channel);
                return(null);
            });

            OtherThread.get().waitUntilWaiting();
            clock.Forward(6, TimeUnit.SECONDS);

            // expect
            try
            {
                future.get(1, TimeUnit.MINUTES);

                fail("expecting ExecutionException");
            }
            catch (ExecutionException ex)
            {
                assertThat(ex.InnerException, instanceOf(typeof(TransportThrottleException)));
                assertThat(ex.Message, containsString("will be closed because the client did not consume outgoing buffers for"));
            }
        }
예제 #4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldSlowlyReduceTheNumberOfFlyweightsInThePoolWhenFlyweightsAreReleased()
        internal virtual void ShouldSlowlyReduceTheNumberOfFlyweightsInThePoolWhenFlyweightsAreReleased()
        {
            // given
            const int minSize = 50;
            const int maxSize = 200;

            StatefulMonitor stateMonitor = new StatefulMonitor();
            FakeClock       clock        = new FakeClock();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LinkedQueuePool<Object> pool = getLinkedQueuePool(stateMonitor, clock, MIN_SIZE);
            LinkedQueuePool <object>          pool    = GetLinkedQueuePool(stateMonitor, clock, minSize);
            IList <FlyweightHolder <object> > holders = new LinkedList <FlyweightHolder <object> >();

            BuildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects(maxSize, clock, pool, holders);

            // when
            // After the peak, stay below MIN_SIZE concurrent usage, using up all already present Flyweights.
            clock.Forward(110, TimeUnit.MILLISECONDS);
            for (int i = 0; i < maxSize; i++)
            {
                AcquireFromPool(pool, 1)[0].release();
            }

            // then

            // currentPeakSize must have reset from the latest alarm to MIN_SIZE.
            assertEquals(1, stateMonitor.CurrentPeakSize.get());                 // Alarm
            // targetSize must be set to MIN_SIZE since currentPeakSize was that 2 alarms ago and didn't increase
            assertEquals(minSize, stateMonitor.TargetSize.get());
            // Only pooled Flyweights must be used, disposing what is in excess
            // +1 for the alarm from buildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects
            assertEquals(maxSize - minSize + 1, stateMonitor.DisposedConflict.get());
        }
예제 #5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldTimeoutGracefully()
        internal virtual void ShouldTimeoutGracefully()
        {
            FakeClock clock = new FakeClock();

            LinkedQueuePool.CheckStrategy timeStrategy = new LinkedQueuePool.CheckStrategy_TimeoutCheckStrategy(100, clock);

            while (clock.AsLong <= 100)
            {
                assertFalse(timeStrategy.ShouldCheck());
                clock.Forward(10, TimeUnit.MILLISECONDS);
            }

            assertTrue(timeStrategy.ShouldCheck());

            clock.Forward(1, TimeUnit.MILLISECONDS);
            assertFalse(timeStrategy.ShouldCheck());
        }
예제 #6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldTimeoutGracefully()
        public virtual void ShouldTimeoutGracefully()
        {
            FakeClock clock = FakeClocks;

            ResourcePool.CheckStrategy timeStrategy = new ResourcePool.CheckStrategy_TimeoutCheckStrategy(TIMEOUT_MILLIS, clock);

            while (clock.Millis() <= TIMEOUT_MILLIS)
            {
                assertFalse(timeStrategy.ShouldCheck());
                clock.Forward(10, TimeUnit.MILLISECONDS);
            }

            assertTrue(timeStrategy.ShouldCheck());

            clock.Forward(1, TimeUnit.MILLISECONDS);
            assertFalse(timeStrategy.ShouldCheck());
        }
예제 #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test @Resources.Life(STARTED) public void shouldNotEndUpInBrokenStateAfterRotationFailure() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotEndUpInBrokenStateAfterRotationFailure()
        {
            // GIVEN
            FakeClock         clock             = Clocks.fakeClock();
            CallTrackingClock callTrackingClock = new CallTrackingClock(clock);
            CountsTracker     tracker           = ResourceManager.managed(NewTracker(callTrackingClock, EmptyVersionContextSupplier.EMPTY));
            int labelId = 1;

            using (Org.Neo4j.Kernel.Impl.Api.CountsAccessor_Updater tx = tracker.Apply(2).get())
            {
                tx.IncrementNodeCount(labelId, 1);                           // now at 1
            }

            // WHEN
            System.Predicate <Thread> arrived  = thread => stackTraceContains(thread, all(classNameContains("Rotation"), methodIs("rotate")));
            Future <object>           rotation = Threading.executeAndAwait(t => t.rotate(4), tracker, arrived, 1, SECONDS);

            using (Org.Neo4j.Kernel.Impl.Api.CountsAccessor_Updater tx = tracker.Apply(3).get())
            {
                tx.IncrementNodeCount(labelId, 1);                           // now at 2
            }
            while (callTrackingClock.CallsToNanos() == 0)
            {
                Thread.Sleep(10);
            }
            clock.Forward(Config.defaults().get(GraphDatabaseSettings.counts_store_rotation_timeout).toMillis() * 2, MILLISECONDS);
            try
            {
                rotation.get();
                fail("Should've failed rotation due to timeout");
            }
            catch (ExecutionException e)
            {
                // good
                assertTrue(e.InnerException is RotationTimeoutException);
            }

            // THEN
            Org.Neo4j.Register.Register_DoubleLongRegister register = Registers.newDoubleLongRegister();
            tracker.Get(CountsKeyFactory.nodeKey(labelId), register);
            assertEquals(2, register.ReadSecond());

            // and WHEN later attempting rotation again
            using (Org.Neo4j.Kernel.Impl.Api.CountsAccessor_Updater tx = tracker.Apply(4).get())
            {
                tx.IncrementNodeCount(labelId, 1);                           // now at 3
            }
            tracker.Rotate(4);

            // THEN
            tracker.Get(CountsKeyFactory.nodeKey(labelId), register);
            assertEquals(3, register.ReadSecond());
        }
예제 #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void mustNotLogMessagesWithinConfiguredTimeLimit()
        public virtual void MustNotLogMessagesWithinConfiguredTimeLimit()
        {
            FakeClock clock = DefaultFakeClock;

            _logger.setTimeLimit(1, TimeUnit.MILLISECONDS, clock);
            _logMethod.log(_logger, "### AAA ###");
            _logMethod.log(_logger, "### BBB ###");
            clock.Forward(1, TimeUnit.MILLISECONDS);
            _logMethod.log(_logger, "### CCC ###");

            _logProvider.rawMessageMatcher().assertContains(containsString("### AAA ###"));
            _logProvider.assertNone(CurrentLog(inLog(typeof(CappedLogger)), containsString("### BBB ###")));
            _logProvider.rawMessageMatcher().assertContains(containsString("### CCC ###"));
        }
예제 #9
0
        private void BuildAPeakOfAcquiredFlyweightsAndTriggerAlarmWithSideEffects(int maxSize, FakeClock clock, LinkedQueuePool <object> pool, IList <FlyweightHolder <object> > holders)
        {
            ((IList <FlyweightHolder <object> >)holders).AddRange(AcquireFromPool(pool, maxSize));

            clock.Forward(110, TimeUnit.MILLISECONDS);

            // "Ring the bell" only on acquisition, of course.
            ((IList <FlyweightHolder <object> >)holders).AddRange(AcquireFromPool(pool, 1));

            foreach (FlyweightHolder holder in holders)
            {
                holder.release();
            }
        }
예제 #10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRateLimitCalls()
        public virtual void ShouldRateLimitCalls()
        {
            // given
            int       intervalMillis = 10;
            FakeClock clock          = Clocks.fakeClock();

            System.Action <ThreadStart> cap = rateLimiter(Duration.ofMillis(intervalMillis), clock);
            AtomicInteger cnt = new AtomicInteger();
            ThreadStart   op  = cnt.incrementAndGet;

            // when
            cap(op);
            cap(op);
            cap(op);

            // then
            assertThat(cnt.get(), equalTo(1));

            // when
            clock.Forward(intervalMillis, MILLISECONDS);
            cap(op);
            cap(op);
            cap(op);

            // then
            assertThat(cnt.get(), equalTo(2));

            // when
            clock.Forward(1000 * intervalMillis, MILLISECONDS);
            cap(op);
            cap(op);
            cap(op);

            // then
            assertThat(cnt.get(), equalTo(3));
        }
예제 #11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldOnlyAllowOneThreadPerInterval() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldOnlyAllowOneThreadPerInterval()
        {
            // given
            int intervalMillis = 10;
            int nThreads       = 10;
            int iterations     = 100;

            FakeClock clock = Clocks.fakeClock();

            System.Action <ThreadStart> cap = rateLimiter(Duration.ofMillis(intervalMillis), clock);
            AtomicInteger cnt = new AtomicInteger();
            ThreadStart   op  = cnt.incrementAndGet;

            for (int iteration = 1; iteration <= iterations; iteration++)
            {
                // given
                clock.Forward(intervalMillis, MILLISECONDS);
                System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);

                ExecutorService es = Executors.newCachedThreadPool();
                for (int j = 0; j < nThreads; j++)
                {
                    es.submit(() =>
                    {
                        try
                        {
                            latch.await();
                        }
                        catch (InterruptedException e)
                        {
                            Console.WriteLine(e.ToString());
                            Console.Write(e.StackTrace);
                        }
                        cap(op);
                    });
                }

                // when
                latch.Signal();
                es.shutdown();
                es.awaitTermination(10, SECONDS);

                // then
                assertThat(cnt.get(), equalTo(iteration));
            }
        }
예제 #12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void mustOnlyLogMessagesThatPassBothLimits()
        public virtual void MustOnlyLogMessagesThatPassBothLimits()
        {
            FakeClock clock = DefaultFakeClock;

            _logger.CountLimit = 2;
            _logger.setTimeLimit(1, TimeUnit.MILLISECONDS, clock);
            _logMethod.log(_logger, "### AAA ###");
            _logMethod.log(_logger, "### BBB ###");                 // Filtered by the time limit
            clock.Forward(1, TimeUnit.MILLISECONDS);
            _logMethod.log(_logger, "### CCC ###");                 // Filtered by the count limit
            _logger.reset();
            _logMethod.log(_logger, "### DDD ###");

            _logProvider.rawMessageMatcher().assertContains(containsString("### AAA ###"));
            _logProvider.assertNone(CurrentLog(inLog(typeof(CappedLogger)), containsString("### BBB ###")));
            _logProvider.assertNone(CurrentLog(inLog(typeof(CappedLogger)), containsString("### CCC ###")));
            _logProvider.rawMessageMatcher().assertContains(containsString("### DDD ###"));
        }
예제 #13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void unsettingTimeLimitMustLetMessagesThrough()
        public virtual void UnsettingTimeLimitMustLetMessagesThrough()
        {
            FakeClock clock = DefaultFakeClock;

            _logger.setTimeLimit(1, TimeUnit.MILLISECONDS, clock);
            _logMethod.log(_logger, "### AAA ###");
            _logMethod.log(_logger, "### BBB ###");
            clock.Forward(1, TimeUnit.MILLISECONDS);
            _logMethod.log(_logger, "### CCC ###");
            _logMethod.log(_logger, "### DDD ###");
            _logger.unsetTimeLimit();               // Note that we are not advancing the clock!
            _logMethod.log(_logger, "### EEE ###");

            _logProvider.rawMessageMatcher().assertContains(containsString("### AAA ###"));
            _logProvider.assertNone(CurrentLog(inLog(typeof(CappedLogger)), containsString("### BBB ###")));
            _logProvider.rawMessageMatcher().assertContains(containsString("### CCC ###"));
            _logProvider.assertNone(CurrentLog(inLog(typeof(CappedLogger)), containsString("### DDD ###")));
            _logProvider.rawMessageMatcher().assertContains(containsString("### EEE ###"));
        }
예제 #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldUpdateTargetSizeWhenSpikesOccur()
        internal virtual void ShouldUpdateTargetSizeWhenSpikesOccur()
        {
            // given
            const int minSize = 5;
            const int maxSize = 10;

            StatefulMonitor stateMonitor = new StatefulMonitor();
            FakeClock       clock        = new FakeClock();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LinkedQueuePool<Object> pool = getLinkedQueuePool(stateMonitor, clock, MIN_SIZE);
            LinkedQueuePool <object> pool = GetLinkedQueuePool(stateMonitor, clock, minSize);
            // when
            IList <FlyweightHolder <object> > holders = AcquireFromPool(pool, maxSize);

            clock.Forward(110, TimeUnit.MILLISECONDS);
            ((IList <FlyweightHolder <object> >)holders).AddRange(AcquireFromPool(pool, 1));                    // Needed to trigger the alarm

            // then
            assertEquals(maxSize + 1, stateMonitor.CurrentPeakSize.get());
            // We have not released anything, so targetSize will not be reduced
            assertEquals(maxSize + 1, stateMonitor.TargetSize.get());                 // + 1 from the acquire
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void throwsWhenTxAwaitDurationExpires()
        public virtual void ThrowsWhenTxAwaitDurationExpires()
        {
            long lastClosedTransactionId = 100;

            System.Func <TransactionIdStore> txIdStore = () => FixedTxIdStore(lastClosedTransactionId);
            Duration  txAwaitDuration = Duration.ofSeconds(42);
            FakeClock clock           = new FakeClock();

            DatabaseAvailabilityGuard databaseAvailabilityGuard = spy(new DatabaseAvailabilityGuard(DEFAULT_DATABASE_NAME, clock, NullLog.Instance));

            when(databaseAvailabilityGuard.Available).then(invocation =>
            {
                // move clock forward on the first availability check
                // this check is executed on every tx id polling iteration
                bool available = ( bool )invocation.callRealMethod();
                clock.Forward(txAwaitDuration.Seconds + 1, SECONDS);
                return(available);
            });

            TransactionStateMachineV1SPI txSpi = CreateTxSpi(txIdStore, txAwaitDuration, databaseAvailabilityGuard, clock);

            Future <Void> result = OtherThread.execute(state =>
            {
                txSpi.AwaitUpToDate(lastClosedTransactionId + 42);
                return(null);
            });

            try
            {
                result.get(20, SECONDS);
            }
            catch (Exception e)
            {
                assertThat(e, instanceOf(typeof(ExecutionException)));
                assertThat(e.InnerException, instanceOf(typeof(TransactionFailureException)));
            }
        }
예제 #16
0
 private void ExceedTimeout(FakeClock clock)
 {
     clock.Forward(_timeoutExceedMillis, TimeUnit.MILLISECONDS);
 }