示例#1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotRunASampleJobWhichIsAlreadyRunning() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotRunASampleJobWhichIsAlreadyRunning()
        {
            // given
            when(_config.jobLimit()).thenReturn(2);
            JobScheduler            jobScheduler = createInitialisedScheduler();
            IndexSamplingJobTracker jobTracker   = new IndexSamplingJobTracker(_config, jobScheduler);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch latch = new org.neo4j.test.DoubleLatch();
            DoubleLatch latch = new DoubleLatch();

            // when
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger count = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger count = new AtomicInteger(0);

            assertTrue(jobTracker.CanExecuteMoreSamplingJobs());
            IndexSamplingJob job = new IndexSamplingJobAnonymousInnerClass(this, latch, count);

            jobTracker.ScheduleSamplingJob(job);
            jobTracker.ScheduleSamplingJob(job);

            latch.StartAndWaitForAllToStart();
            latch.WaitForAllToFinish();

            assertEquals(1, count.get());
        }
示例#2
0
        private int TryGetNumberOfAvailablePages(int keepFree)
        {
            object freelistHead = FreelistHead;

            if (freelistHead == null)
            {
                return(keepFree);
            }
            else if (freelistHead.GetType() == typeof(FreePage))
            {
                int availablePages = (( FreePage )freelistHead).Count;
                if (availablePages < keepFree)
                {
                    return(keepFree - availablePages);
                }
            }
            else if (freelistHead.GetType() == typeof(AtomicInteger))
            {
                AtomicInteger counter = ( AtomicInteger )freelistHead;
                long          count   = Pages.PageCount - counter.get();
                if (count < keepFree)
                {
                    return(count < 0 ? keepFree : ( int )(keepFree - count));
                }
            }
            return(UNKNOWN_AVAILABLE_PAGES);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createdWorkerThreadsShouldContainConnectorName() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CreatedWorkerThreadsShouldContainConnectorName()
        {
            AtomicInteger            executeBatchCompletionCount = new AtomicInteger();
            AtomicReference <Thread> poolThread     = new AtomicReference <Thread>();
            AtomicReference <string> poolThreadName = new AtomicReference <string>();

            string         id         = System.Guid.randomUUID().ToString();
            BoltConnection connection = NewConnection(id);

            when(connection.HasPendingJobs()).thenAnswer(inv =>
            {
                executeBatchCompletionCount.incrementAndGet();
                return(false);
            });
            when(connection.ProcessNextBatch()).thenAnswer(inv =>
            {
                poolThread.set(Thread.CurrentThread);
                poolThreadName.set(Thread.CurrentThread.Name);
                return(true);
            });

            _boltScheduler.start();
            _boltScheduler.created(connection);
            _boltScheduler.enqueued(connection, Jobs.noop());

            Predicates.await(() => executeBatchCompletionCount.get() > 0, 1, MINUTES);

            assertThat(poolThread.get().Name, not(equalTo(poolThreadName.get())));
            assertThat(poolThread.get().Name, containsString(string.Format("[{0}]", CONNECTOR_KEY)));
            assertThat(poolThread.get().Name, not(containsString(string.Format("[{0}]", connection.RemoteAddress()))));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createdWorkerThreadsShouldContainConnectorNameAndRemoteAddressInTheirNamesWhenActive() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CreatedWorkerThreadsShouldContainConnectorNameAndRemoteAddressInTheirNamesWhenActive()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<String> capturedThreadName = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <string> capturedThreadName = new AtomicReference <string>();

            AtomicInteger  processNextBatchCount = new AtomicInteger();
            string         id            = System.Guid.randomUUID().ToString();
            BoltConnection connection    = NewConnection(id);
            AtomicBoolean  exitCondition = new AtomicBoolean();

            when(connection.ProcessNextBatch()).thenAnswer(inv =>
            {
                capturedThreadName.set(Thread.CurrentThread.Name);
                processNextBatchCount.incrementAndGet();
                return(AwaitExit(exitCondition));
            });

            _boltScheduler.start();
            _boltScheduler.created(connection);
            _boltScheduler.enqueued(connection, Jobs.noop());

            Predicates.await(() => processNextBatchCount.get() > 0, 1, MINUTES);

            assertThat(capturedThreadName.get(), containsString(string.Format("[{0}]", CONNECTOR_KEY)));
            assertThat(capturedThreadName.get(), containsString(string.Format("[{0}]", connection.RemoteAddress())));

            exitCondition.set(true);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldKeepHighestDuringConcurrentOfferings() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldKeepHighestDuringConcurrentOfferings()
        {
            // GIVEN
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final HighestTransactionId highest = new HighestTransactionId(-1, -1, -1);
            HighestTransactionId highest = new HighestTransactionId(-1, -1, -1);
            Race race     = new Race();
            int  updaters = max(2, Runtime.availableProcessors());
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger accepted = new java.util.concurrent.atomic.AtomicInteger();
            AtomicInteger accepted = new AtomicInteger();

            for (int i = 0; i < updaters; i++)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long id = i + 1;
                long id = i + 1;
                race.AddContestant(() =>
                {
                    if (highest.Offer(id, id, id))
                    {
                        accepted.incrementAndGet();
                    }
                });
            }

            // WHEN
            race.Go();

            // THEN
            assertTrue(accepted.get() > 0);
            assertEquals(updaters, highest.Get().transactionId());
        }
示例#6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void initialisationMustBeIdempotent()
        public virtual void InitialisationMustBeIdempotent()
        {
            _updatePuller.start();
            _updatePuller.start();
            _updatePuller.start();
            assertThat(_scheduledJobs.get(), @is(1));
        }
示例#7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void twoRoundRobin()
        public virtual void TwoRoundRobin()
        {
            ManagedCluster cluster = StartCluster(4, 2, HaSettings.TxPushStrategy.RoundRobin);

            HighlyAvailableGraphDatabase master = cluster.Master;
            Monitors      monitors            = master.DependencyResolver.resolveDependency(typeof(Monitors));
            AtomicInteger totalMissedReplicas = new AtomicInteger();

            monitors.AddMonitorListener((MasterTransactionCommitProcess.Monitor)totalMissedReplicas.addAndGet);
            long txId  = GetLastTx(master);
            int  count = 15;

            for (int i = 0; i < count; i++)
            {
                CreateTransactionOnMaster(cluster);
            }

            long min = -1;
            long max = -1;

            foreach (GraphDatabaseAPI db in cluster.AllMembers)
            {
                long tx = GetLastTx(db);
                min = min == -1 ? tx : min(min, tx);
                max = max == -1 ? tx : max(max, tx);
            }

            assertEquals(txId + count, max);
            assertTrue("There should be members with transactions in the cluster", min != -1 && max != -1);

            int minLaggingBehindThreshold = 1 + totalMissedReplicas.get();

            assertThat("There should at most be a txId gap of 1 among the cluster members since the transaction pushing " + "goes in a round robin fashion. min:" + min + ", max:" + max, ( int )(max - min), lessThanOrEqualTo(minLaggingBehindThreshold));
        }
示例#8
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: public void checkCounts(org.neo4j.kernel.impl.api.CountsAccessor counts, final org.neo4j.consistency.report.ConsistencyReporter reporter, org.neo4j.helpers.progress.ProgressMonitorFactory progressFactory)
        public virtual void CheckCounts(CountsAccessor counts, ConsistencyReporter reporter, ProgressMonitorFactory progressFactory)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int nodes = nodeCounts.size();
            int nodes = _nodeCounts.size();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int relationships = relationshipCounts.size();
            int relationships = _relationshipCounts.size();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int total = nodes + relationships;
            int total = nodes + relationships;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger nodeEntries = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger nodeEntries = new AtomicInteger(0);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger relationshipEntries = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger relationshipEntries = new AtomicInteger(0);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.helpers.progress.ProgressListener listener = progressFactory.singlePart("Checking node and relationship counts", total);
            ProgressListener listener = progressFactory.SinglePart("Checking node and relationship counts", total);

            listener.Started();
            Counts.accept(new CountsVisitor_AdapterAnonymousInnerClass(this, reporter, nodeEntries, relationshipEntries, listener));
            reporter.ForCounts(new CountsEntry(nodeKey(WILDCARD), nodeEntries.get()), CHECK_NODE_KEY_COUNT);
            reporter.ForCounts(new CountsEntry(relationshipKey(WILDCARD, WILDCARD, WILDCARD), relationshipEntries.get()), CHECK_RELATIONSHIP_KEY_COUNT);
            listener.Done();
        }
示例#9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void recurringJobWithExceptionShouldKeepRunning() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RecurringJobWithExceptionShouldKeepRunning()
        {
            // given
            RobustJobSchedulerWrapper robustWrapper = new RobustJobSchedulerWrapper(_actualScheduler, _log);

            AtomicInteger count = new AtomicInteger();

            System.InvalidOperationException e = new System.InvalidOperationException();

            // when
            int       nRuns     = 100;
            JobHandle jobHandle = robustWrapper.ScheduleRecurring(Group.HZ_TOPOLOGY_REFRESH, 1, () =>
            {
                if (count.get() < nRuns)
                {
                    count.incrementAndGet();
                    throw e;
                }
            });

            // then
            assertEventually("run count", count.get, Matchers.equalTo(nRuns), _defaultTimeoutMs, MILLISECONDS);
            jobHandle.Cancel(true);
            verify(_log, timeout(_defaultTimeoutMs).times(nRuns)).warn("Uncaught exception", e);
        }
示例#10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Deployment public void testExecutionListenerWithMultiInstanceBody()
        public virtual void testExecutionListenerWithMultiInstanceBody()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger eventCountForMultiInstanceBody = new java.util.concurrent.atomic.AtomicInteger();
            AtomicInteger eventCountForMultiInstanceBody = new AtomicInteger();

            EmbeddedProcessApplication processApplication = new EmbeddedProcessApplicationAnonymousInnerClass7(this, eventCountForMultiInstanceBody);

            // register app so that it is notified about events
            managementService.registerProcessApplication(deploymentId, processApplication.Reference);


            // start process instance
            runtimeService.startProcessInstanceByKey("executionListener");

            // complete task
            IList <Task> miTasks = taskService.createTaskQuery().list();

            foreach (Task task in miTasks)
            {
                taskService.complete(task.Id);
            }

            // 2 events are expected: one for mi body start; one for mi body end
            assertEquals(2, eventCountForMultiInstanceBody.get());
        }
示例#11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ParameterizedTest @ValueSource(ints = {0, 1}) @DisabledOnOs(org.junit.jupiter.api.condition.OS.WINDOWS) void mustCloseFilesIfTakingFileLockThrows(int noChannelStriping) throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void MustCloseFilesIfTakingFileLockThrows(int noChannelStriping)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger openFilesCounter = new java.util.concurrent.atomic.AtomicInteger();
            AtomicInteger      openFilesCounter = new AtomicInteger();
            PageSwapperFactory factory          = CreateSwapperFactory();

            factory.open(new DelegatingFileSystemAbstractionAnonymousInnerClass(this, _fileSystem, openFilesCounter)
                         , Configuration.EMPTY);
            File file = TestDir.file("file");

            try
            {
                using (StoreChannel ch = _fileSystem.create(file), FileLock ignore = ch.TryLock())
                {
                    CreateSwapper(factory, file, 4, NoCallback, false, Bool(noChannelStriping)).close();
                    fail("Creating a page swapper for a locked channel should have thrown");
                }
            }
            catch (FileLockException)
            {
                // As expected.
            }
            assertThat(openFilesCounter.get(), @is(0));
        }
        //-------------------------------------------------------------------------
        public virtual void test_forEach()
        {
            LocalDateDoubleTimeSeries @base   = LocalDateDoubleTimeSeries.builder().putAll(DATES_2010_14, VALUES_10_14).build();
            AtomicInteger             counter = new AtomicInteger();

            @base.forEach((date, value) => counter.addAndGet((int)value));
            assertEquals(counter.get(), 10 + 11 + 12 + 13 + 14);
        }
示例#13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void singleWithDefaultMustAutoCloseEmptyIterator()
        internal virtual void SingleWithDefaultMustAutoCloseEmptyIterator()
        {
            AtomicInteger counter = new AtomicInteger();
            CountingPrimitiveLongIteratorResource itr = new CountingPrimitiveLongIteratorResource(PrimitiveLongCollections.EmptyIterator(), counter);

            assertEquals(PrimitiveLongCollections.Single(itr, 2), 2);
            assertEquals(1, counter.get());
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createShouldNotStartCoreThreadsIfNotAsked()
        public virtual void CreateShouldNotStartCoreThreadsIfNotAsked()
        {
            AtomicInteger threadCounter = new AtomicInteger();

            _factory.create(5, 10, Duration.ZERO, 0, false, NewThreadFactoryWithCounter(threadCounter));

            assertEquals(0, threadCounter.get());
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotStartOtherSamplingWhenSamplingAllTheIndexes()
        public virtual void ShouldNotStartOtherSamplingWhenSamplingAllTheIndexes()
        {
            // given
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger totalCount = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger totalCount = new AtomicInteger(0);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger concurrentCount = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger concurrentCount = new AtomicInteger(0);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch jobLatch = new org.neo4j.test.DoubleLatch();
            DoubleLatch jobLatch = new DoubleLatch();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch testLatch = new org.neo4j.test.DoubleLatch();
            DoubleLatch testLatch = new DoubleLatch();

            IndexSamplingJobFactory jobFactory = (_indexId, proxy) =>
            {
                if (!concurrentCount.compareAndSet(0, 1))
                {
                    throw new System.InvalidOperationException("count !== 0 on create");
                }
                totalCount.incrementAndGet();
                jobLatch.WaitForAllToStart();
                testLatch.StartAndWaitForAllToStart();
                jobLatch.WaitForAllToFinish();
                concurrentCount.decrementAndGet();
                testLatch.Finish();
                return(null);
            };

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexSamplingController controller = new IndexSamplingController(samplingConfig, jobFactory, jobQueue, tracker, snapshotProvider, scheduler, always(true));
            IndexSamplingController controller = new IndexSamplingController(_samplingConfig, jobFactory, _jobQueue, _tracker, _snapshotProvider, _scheduler, Always(true));

            when(_tracker.canExecuteMoreSamplingJobs()).thenReturn(true);
            when(_indexProxy.State).thenReturn(ONLINE);

            // when running once
            (new Thread(RunController(controller, TRIGGER_REBUILD_UPDATED))).Start();

            jobLatch.StartAndWaitForAllToStart();
            testLatch.WaitForAllToStart();

            // then blocking on first job
            assertEquals(1, concurrentCount.get());

            // when running a second time
            controller.SampleIndexes(BACKGROUND_REBUILD_UPDATED);

            // then no concurrent job execution
            jobLatch.Finish();
            testLatch.WaitForAllToFinish();

            // and finally exactly one job has run to completion
            assertEquals(0, concurrentCount.get());
            assertEquals(1, totalCount.get());
        }
示例#16
0
        public override bool Equals(object o)
        {
            if (this == o)
            {
                return(true);
            }
            if (o == null || this.GetType() != o.GetType())
            {
                return(false);
            }
            if (!base.Equals(o))
            {
                return(false);
            }
            IndexDefineCommand that = ( IndexDefineCommand )o;

            return(_nextIndexNameId.get() == that._nextIndexNameId.get() && _nextKeyId.get() == that._nextKeyId.get() && Objects.Equals(_indexNameIdRange, that._indexNameIdRange) && Objects.Equals(_keyIdRange, that._keyIdRange) && Objects.Equals(_idToIndexName, that._idToIndexName) && Objects.Equals(_idToKey, that._idToKey));
        }
示例#17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void runTest() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RunTest()
        {
            for (int i = 0; i < N_THREADS; i++)
            {
                _service.submit(_task);
            }
            _service.awaitTermination(10, TimeUnit.SECONDS);
            assertThat(_counter.get(), equalTo(N_THREADS));
        }
示例#18
0
        // Tests schedules a recurring job to run 5 times with 100ms in between.
        // The timeout of 10s should be enough.
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 10_000) public void shouldRunRecurringJob() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRunRecurringJob()
        {
            // Given
            long period = 10;
            int  count  = 5;

            _life.start();

            // When
            _scheduler.scheduleRecurring(Group.INDEX_POPULATION, _countInvocationsJob, period, MILLISECONDS);
            AwaitInvocationCount(count);
            _scheduler.shutdown();

            // Then assert that the recurring job was stopped (when the scheduler was shut down)
            int actualInvocations = _invocations.get();

            sleep(period * 5);
            assertThat(_invocations.get(), equalTo(actualInvocations));
        }
示例#19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldClearFileOnFirstUse() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldClearFileOnFirstUse()
        {
            // given
            EphemeralFileSystemAbstraction fsa = _fileSystemRule.get();

            fsa.Mkdir(_testDir.directory());

            int rotationCount = 10;

            DurableStateStorage <AtomicInteger> storage = new DurableStateStorage <AtomicInteger>(fsa, _testDir.directory(), "state", new AtomicIntegerMarshal(), rotationCount, NullLogProvider.Instance);
            int largestValueWritten = 0;

            using (Lifespan lifespan = new Lifespan(storage))
            {
                for ( ; largestValueWritten < rotationCount * 2; largestValueWritten++)
                {
                    storage.PersistStoreData(new AtomicInteger(largestValueWritten));
                }
            }

            // now both files are full. We reopen, then write some more.
            storage = _lifeRule.add(new DurableStateStorage <>(fsa, _testDir.directory(), "state", new AtomicIntegerMarshal(), rotationCount, NullLogProvider.Instance));

            storage.PersistStoreData(new AtomicInteger(largestValueWritten++));
            storage.PersistStoreData(new AtomicInteger(largestValueWritten++));
            storage.PersistStoreData(new AtomicInteger(largestValueWritten));

            /*
             * We have written stuff in fileA but not gotten to the end (resulting in rotation). The largestValueWritten
             * should nevertheless be correct
             */
            ByteBuffer   forReadingBackIn = ByteBuffer.allocate(10_000);
            StoreChannel lastWrittenTo    = fsa.Open(StateFileA(), OpenMode.READ);

            lastWrittenTo.read(forReadingBackIn);
            forReadingBackIn.flip();

            AtomicInteger lastRead = null;

            while (true)
            {
                try
                {
                    lastRead = new AtomicInteger(forReadingBackIn.Int);
                }
                catch (BufferUnderflowException)
                {
                    break;
                }
            }

            // then
            assertNotNull(lastRead);
            assertEquals(largestValueWritten, lastRead.get());
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createdExecutorShouldExecuteSubmittedTasks() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CreatedExecutorShouldExecuteSubmittedTasks()
        {
            AtomicBoolean exitCondition = new AtomicBoolean(false);
            AtomicInteger threadCounter = new AtomicInteger(0);

            _executorService = _factory.create(0, 1, Duration.ZERO, 0, false, NewThreadFactoryWithCounter(threadCounter));

            assertNotNull(_executorService);
            assertEquals(0, threadCounter.get());

            Future task1 = _executorService.submit(NewInfiniteWaitingRunnable(exitCondition));

            assertEquals(1, threadCounter.get());

            exitCondition.set(true);

            assertNull(task1.get(1, MINUTES));
            assertTrue(task1.Done);
            assertFalse(task1.Cancelled);
        }
示例#21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldForwardLockIdentifierToMaster() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldForwardLockIdentifierToMaster()
        {
            // Given
            when(_master.commit(_requestContext, _tx)).thenReturn(_response);

            // When
            _commitProcess.commit(new TransactionToApply(_tx), CommitEvent.NULL, TransactionApplicationMode.INTERNAL);

            // Then
            assertThat(_lastSeenEventIdentifier.get(), @is(1337));
        }
示例#22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void eventHandlersAreOnlyInvokedOnceDuringShutdown()
        public virtual void EventHandlersAreOnlyInvokedOnceDuringShutdown()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger counter = new java.util.concurrent.atomic.AtomicInteger();
            AtomicInteger counter = new AtomicInteger();

            _graphDb.registerKernelEventHandler(new KernelEventHandlerAnonymousInnerClass(this, counter));
            _graphDb.shutdown();
            _graphDb.shutdown();
            assertEquals(1, counter.get());
        }
        //-------------------------------------------------------------------------
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(enabled = false) public void test_javaBroken() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void test_javaBroken()
        {
            // uncomment system out to see how broken it is
            // very specific format instance needed
            DecimalFormat format = new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH));
            Random        random = new Random(1);

            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            AtomicInteger broken      = new AtomicInteger();
            int           threadCount = 15;

            for (int i = 0; i < threadCount; i++)
            {
                ThreadStart runner = () =>
                {
                    try
                    {
                        latch.await();
                        int    val = random.Next(999);
                        string a   = format.format((double)val);
                        string b   = Convert.ToInt32(val).ToString();
                        Console.WriteLine(a + " " + b);
                        if (!a.Equals(b))
                        {
                            broken.incrementAndGet();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception: " + ex.Message);
                    }
                };
                (new Thread(runner, "TestThread" + i)).Start();
            }
            // start all threads together
            latch.Signal();
            Thread.Sleep(1000);
            Console.WriteLine("Broken: " + broken.get());
            assertTrue(broken.get() > 0);
        }
示例#24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Deployment public void testExecutionListenerWithTimerBoundaryEvent()
        public virtual void testExecutionListenerWithTimerBoundaryEvent()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger eventCount = new java.util.concurrent.atomic.AtomicInteger();
            AtomicInteger eventCount = new AtomicInteger();

            EmbeddedProcessApplication processApplication = new EmbeddedProcessApplicationAnonymousInnerClass5(this, eventCount);

            // register app so that it is notified about events
            managementService.registerProcessApplication(deploymentId, processApplication.Reference);

            // 1. (start)startEvent(end) -(take)-> (start)userTask(end) -(take)-> (start)endEvent(end) (8 Events)

            // start process instance
            runtimeService.startProcessInstanceByKey("executionListener");

            // complete task
            Task task = taskService.createTaskQuery().singleResult();

            taskService.complete(task.Id);

            assertEquals(10, eventCount.get());

            // reset counter
            eventCount.set(0);

            // 2. (start)startEvent(end) -(take)-> (start)userTask(end)/(start)timerBoundaryEvent(end) -(take)-> (start)endEvent(end) (10 Events)

            // start process instance
            runtimeService.startProcessInstanceByKey("executionListener");

            // fire timer event
            Job job = managementService.createJobQuery().singleResult();

            managementService.executeJob(job.Id);

            assertEquals(12, eventCount.get());
        }
示例#25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void updateDynamicShouldInformRegisteredListeners()
        public virtual void UpdateDynamicShouldInformRegisteredListeners()
        {
            Config        config  = Config.Builder().withConfigClasses(singletonList(new MyDynamicSettings())).build();
            AtomicInteger counter = new AtomicInteger(0);

            config.RegisterDynamicUpdateListener(MyDynamicSettings.BoolSetting, (previous, update) =>
            {
                counter.AndIncrement;
                assertTrue(previous);
                assertFalse(update);
            });
            config.UpdateDynamicSetting(MyDynamicSettings.BoolSetting.name(), "false", ORIGIN);
            assertThat(counter.get(), @is(1));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldInvokeHandleSchedulingErrorIfNoThreadsAvailable() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldInvokeHandleSchedulingErrorIfNoThreadsAvailable()
        {
            AtomicInteger  handleSchedulingErrorCounter = new AtomicInteger(0);
            BoltConnection newConnection = newConnection(System.Guid.randomUUID().ToString());

            doAnswer(NewCountingAnswer(handleSchedulingErrorCounter)).when(newConnection).handleSchedulingError(any());

            BlockAllThreads();

            // register connection
            _boltScheduler.created(newConnection);

            // send a job and wait for it to enter handleSchedulingError and block there
            CompletableFuture.runAsync(() => _boltScheduler.enqueued(newConnection, Jobs.noop()));
            Predicates.awaitForever(() => handleSchedulingErrorCounter.get() > 0, 500, MILLISECONDS);

            // verify that handleSchedulingError is called once
            assertEquals(1, handleSchedulingErrorCounter.get());

            // allow all threads to complete
            _afterExecuteEvent.Signal();
            _afterExecuteBarrier.await();
        }
示例#27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void oneOrTheOtherShouldDeadlock() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void OneOrTheOtherShouldDeadlock()
        {
            AtomicInteger deadlockCount         = new AtomicInteger();
            HighlyAvailableGraphDatabase master = _cluster.Master;
            Node masterA = CreateNodeOnMaster(_testLabel, master);
            Node masterB = CreateNodeOnMaster(_testLabel, master);

            HighlyAvailableGraphDatabase slave = _cluster.AnySlave;

            using (Transaction transaction = slave.BeginTx())
            {
                Node slaveA = slave.GetNodeById(masterA.Id);
                Node slaveB = slave.GetNodeById(masterB.Id);
                System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);

                transaction.AcquireWriteLock(slaveB);

                Thread masterTx = new Thread(() =>
                {
                    try
                    {
                        using (Transaction tx = master.BeginTx())
                        {
                            tx.acquireWriteLock(masterA);
                            latch.Signal();
                            tx.acquireWriteLock(masterB);
                        }
                    }
                    catch (DeadlockDetectedException)
                    {
                        deadlockCount.incrementAndGet();
                    }
                });
                masterTx.Start();
                latch.await();

                try
                {
                    transaction.AcquireWriteLock(slaveA);
                }
                catch (DeadlockDetectedException)
                {
                    deadlockCount.incrementAndGet();
                }
                masterTx.Join();
            }

            assertEquals(1, deadlockCount.get());
        }
示例#28
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));
        }
示例#29
0
 private void AwaitMyTurnToInitialize()
 {
     while (_idQueue.get() < _id - 1)
     {
         try
         {
             Thread.Sleep(10);
         }
         catch (InterruptedException)
         {
             Thread.interrupted();
             break;
         }
     }
 }
 public void run() {
   while (numActiveWorkers.get() != 0) {
     try {
       List<SimilarItems> similarItemsOfABatch = results.poll(10, TimeUnit.MILLISECONDS);
       if (similarItemsOfABatch != null) {
         foreach (SimilarItems similarItems in similarItemsOfABatch) {
           writer.add(similarItems);
           numSimilaritiesProcessed += similarItems.numSimilarItems();
         }
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
        //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
        //ORIGINAL LINE: @Test public void testCloseableScheduleWithFixedDelayAndAdditionalTasks() throws InterruptedException
        //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void testCloseableScheduleWithFixedDelayAndAdditionalTasks()
        {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger outerCounter = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger outerCounter = new AtomicInteger(0);
            Runnable command = () =>
            {
                outerCounter.incrementAndGet();
            };
            executorService.scheduleWithFixedDelay(command, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS);

            CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService);

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger innerCounter = new java.util.concurrent.atomic.AtomicInteger(0);
            AtomicInteger innerCounter = new AtomicInteger(0);
            service.scheduleWithFixedDelay(() =>
            {
                innerCounter.incrementAndGet();
            }, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS);

            Thread.Sleep(DELAY_MS * 4);

            service.close();
            Thread.Sleep(DELAY_MS * 2);

            int innerValue = innerCounter.get();
            Assert.assertTrue(innerValue > 0);

            int value = outerCounter.get();
            Thread.Sleep(DELAY_MS * 2);
            int newValue = outerCounter.get();
            Assert.assertTrue(newValue > value);
            Assert.assertEquals(innerValue, innerCounter.get());

            value = newValue;
            Thread.Sleep(DELAY_MS * 2);
            newValue = outerCounter.get();
            Assert.assertTrue(newValue > value);
            Assert.assertEquals(innerValue, innerCounter.get());
        }