예제 #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCorrectlyDecideToAwaitMergeDependingOnProgress() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldCorrectlyDecideToAwaitMergeDependingOnProgress()
        {
            // given
            BlockBasedIndexPopulator <GenericKey, NativeIndexValue> populator = InstantiatePopulator(NO_MONITOR);
            bool closed = false;

            try
            {
                populator.Add(BatchOfUpdates());

                // when
                Race race = new Race();
                race.AddContestant(throwing(() => populator.scanCompleted(nullInstance)));
                race.AddContestant(throwing(() => populator.close(false)));
                race.Go();
                closed = true;

                // then regardless of who wins (close/merge) after close call returns no files should still be mapped
                EphemeralFileSystemAbstraction ephemeralFileSystem = ( EphemeralFileSystemAbstraction )_fs;
                ephemeralFileSystem.AssertNoOpenFiles();
            }
            finally
            {
                if (!closed)
                {
                    populator.Close(true);
                }
            }
        }
예제 #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void nodeIdsReused() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void NodeIdsReused()
        {
            CreateInitialNodes(Db);
            long initialHighestNodeId = HighestNodeId(Db);

            Race race = new Race();

            for (int i = 0; i < CONTESTANTS_COUNT; i++)
            {
                if (i % 2 == 0)
                {
                    race.AddContestant(new NodeCreator(Db));
                }
                else
                {
                    race.AddContestant(new NodeRemover(Db));
                }
            }

            race.Go();

            int  writeContestants          = CONTESTANTS_COUNT / 2;
            int  createdNodes              = writeContestants * OPERATIONS_COUNT;
            long highestNodeIdWithoutReuse = initialHighestNodeId + createdNodes;

            long currentHighestNodeId = HighestNodeId(Db);

            assertThat(currentHighestNodeId, lessThan(highestNodeIdWithoutReuse));
        }
예제 #3
0
        public virtual void ShouldCopeWithConcurrentIncrementOfProcessorsAndShutdown()
        {
            // GIVEN
            TaskExecutor <Void> executor = new DynamicTaskExecutor <Void>(1, 2, 2, _park, "test");
            Race race = (new Race()).withRandomStartDelays();

            race.AddContestant(executor.close);
            race.AddContestant(() => executor.Processors(1));

            // WHEN
            race.Go(10, SECONDS);

            // THEN we should be able to do so, there was a recent fix here and before that fix
            // shutdown() would hang, that's why we wait for 10 seconds here to cap it if there's an issue.
        }
예제 #4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldShareThreadLocalBuffersStressfully() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void ShouldShareThreadLocalBuffersStressfully()
        {
            // given
            ByteBufferFactory factory = new ByteBufferFactory(() => HEAP_ALLOCATOR, 1024);
            Race race    = new Race();
            int  threads = 10;
            IList <ISet <ByteBuffer> > seenBuffers = new List <ISet <ByteBuffer> >();

            for (int i = 0; i < threads; i++)
            {
                HashSet <ByteBuffer> seen = new HashSet <ByteBuffer>();
                seenBuffers.Add(seen);
                race.AddContestant(() =>
                {
                    for (int j = 0; j < 1000; j++)
                    {
                        ByteBuffer buffer = factory.AcquireThreadLocalBuffer();
                        assertNotNull(buffer);
                        seen.Add(buffer);
                        factory.ReleaseThreadLocalBuffer();
                    }
                }, 1);
            }

            // when
            race.Go();

            // then
            for (int i = 0; i < threads; i++)
            {
                assertEquals(1, seenBuffers[i].Count);
            }
            factory.Close();
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void concurrentCreatingOfIndexesShouldNotInterfere() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConcurrentCreatingOfIndexesShouldNotInterfere()
        {
            // WHEN concurrently creating indexes for different labels
            Race race = new Race();

            for (int i = 0; i < _threads; i++)
            {
                race.AddContestant(IndexCreate(i), 1);
            }
            race.Go();

            // THEN they should all be observed as existing in the end
            using (Transaction tx = Db.beginTx())
            {
                IList <IndexDefinition> indexes = new IList <IndexDefinition> {
                    Db.schema().Indexes
                };
                assertEquals(_threads, indexes.Count);
                ISet <string> labels = new HashSet <string>();
                foreach (IndexDefinition index in indexes)
                {
                    assertTrue(labels.Add(single(index.Labels).name()));
                }
                tx.Success();
            }
        }
예제 #6
0
        public virtual void ShouldKeepHighest()
        {
            // GIVEN
            Race      race      = new Race();
            HighestId highestId = new HighestId();
            int       threads   = Runtime.Runtime.availableProcessors();

            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(threads);
            AtomicLongArray highestIds            = new AtomicLongArray(threads);

            for (int c = 0; c < threads; c++)
            {
                int cc = c;
                race.AddContestant(new RunnableAnonymousInnerClass(this, highestId, latch, highestIds, cc));
            }
            race.WithEndCondition(() => latch.CurrentCount == 0);

            // WHEN
            race.Go();

            long highest = 0;

            for (int i = 0; i < threads; i++)
            {
                highest = max(highest, highestIds.get(i));
            }
            assertEquals(highest, highestId.Get());
        }
예제 #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldSupportConcurrentGet() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldSupportConcurrentGet()
        {
            // GIVEN
            int highLabelId   = 10;
            int numberOfNodes = 100;

            int[][]         expectedLabels = new int[numberOfNodes][];
            NodeLabelsCache cache          = new NodeLabelsCache(NumberArrayFactory_Fields.AutoWithoutPagecache, highLabelId);

            for (int i = 0; i < numberOfNodes; i++)
            {
                cache.Put(i, AsLongArray(expectedLabels[i] = RandomLabels(_random.Next(5), highLabelId)));
            }

            // WHEN
            Race getRace = new Race();

            for (int i = 0; i < 10; i++)
            {
                getRace.AddContestant(new LabelGetter(cache, expectedLabels, numberOfNodes));
            }

            // THEN expected labels should be had (asserted in LabelGetter), and no exceptions (propagated by go())
            getRace.Go();
        }
예제 #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void concurrentSchemaRuleRemove() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConcurrentSchemaRuleRemove()
        {
            SchemaCache cache       = NewSchemaCache();
            int         indexNumber = 20;

            for (int i = 0; i < indexNumber; i++)
            {
                cache.AddSchemaRule(NewIndexRule(i, i, i));
            }
            Race race = new Race();
            int  numberOfDeletions = 10;

            for (int i = 0; i < numberOfDeletions; i++)
            {
                int indexId = i;
                race.AddContestant(() => cache.removeSchemaRule(indexId));
            }
            race.Go();

            assertEquals(indexNumber - numberOfDeletions, Iterables.count(cache.IndexDescriptors()));
            for (int labelId = numberOfDeletions; labelId < indexNumber; labelId++)
            {
                assertEquals(1, Iterators.count(cache.IndexDescriptorsForLabel(labelId)));
            }
            for (int propertyId = numberOfDeletions; propertyId < indexNumber; propertyId++)
            {
                assertEquals(1, Iterators.count(cache.IndexesByProperty(propertyId)));
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void concurrentDroppingOfIndexesShouldNotInterfere() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConcurrentDroppingOfIndexesShouldNotInterfere()
        {
            // GIVEN created indexes
            IList <IndexDefinition> indexes = new List <IndexDefinition>();

            using (Transaction tx = Db.beginTx())
            {
                for (int i = 0; i < _threads; i++)
                {
                    indexes.Add(Db.schema().indexFor(Label(i)).on(KEY).create());
                }
                tx.Success();
            }

            // WHEN dropping them
            Race race = new Race();

            foreach (IndexDefinition index in indexes)
            {
                race.AddContestant(IndexDrop(index), 1);
            }
            race.Go();

            // THEN they should all be observed as dropped in the end
            using (Transaction tx = Db.beginTx())
            {
                assertEquals(0, asList(Db.schema().Indexes).size());
                tx.Success();
            }
        }
예제 #10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void stressIt() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void StressIt()
        {
            Race race = new Race();
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.atomic.AtomicReferenceArray<java.util.List<? extends org.neo4j.kernel.api.index.IndexEntryUpdate<?>>> lastBatches = new java.util.concurrent.atomic.AtomicReferenceArray<>(THREADS);
            AtomicReferenceArray <IList <IndexEntryUpdate <object> > > lastBatches = new AtomicReferenceArray <IList <IndexEntryUpdate <object> > >(THREADS);

            Generator[] generators = new Generator[THREADS];

            _populator.create();
            System.Threading.CountdownEvent insertersDone = new System.Threading.CountdownEvent(THREADS);
            ReadWriteLock updateLock = new ReentrantReadWriteLock(true);

            for (int i = 0; i < THREADS; i++)
            {
                race.AddContestant(Inserter(lastBatches, generators, insertersDone, updateLock, i), 1);
            }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Collection<org.neo4j.kernel.api.index.IndexEntryUpdate<?>> updates = new java.util.ArrayList<>();
            ICollection <IndexEntryUpdate <object> > updates = new List <IndexEntryUpdate <object> >();

            race.AddContestant(Updater(lastBatches, insertersDone, updateLock, updates));

            race.Go();
            _populator.close(true);
            _populator = null;               // to let the after-method know that we've closed it ourselves

            // then assert that a tree built by a single thread ends up exactly the same
            BuildReferencePopulatorSingleThreaded(generators, updates);
            using (IndexAccessor accessor = _indexProvider.getOnlineAccessor(Descriptor, _samplingConfig), IndexAccessor referenceAccessor = _indexProvider.getOnlineAccessor(_descriptor2, _samplingConfig), IndexReader reader = accessor.NewReader(), IndexReader referenceReader = referenceAccessor.NewReader())
            {
                SimpleNodeValueClient entries          = new SimpleNodeValueClient();
                SimpleNodeValueClient referenceEntries = new SimpleNodeValueClient();
                reader.Query(entries, IndexOrder.NONE, HasValues, IndexQuery.exists(0));
                referenceReader.Query(referenceEntries, IndexOrder.NONE, HasValues, IndexQuery.exists(0));
                while (referenceEntries.Next())
                {
                    assertTrue(entries.Next());
                    assertEquals(referenceEntries.Reference, entries.Reference);
                    if (HasValues)
                    {
                        assertEquals(ValueTuple.of(referenceEntries.Values), ValueTuple.of(entries.Values));
                    }
                }
                assertFalse(entries.Next());
            }
        }
예제 #11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void concurrentMixedCreatingAndDroppingOfIndexesShouldNotInterfere() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConcurrentMixedCreatingAndDroppingOfIndexesShouldNotInterfere()
        {
            // GIVEN created indexes
            IList <IndexDefinition> indexesToDrop = new List <IndexDefinition>();
            int creates = _threads / 2;
            int drops   = _threads - creates;

            using (Transaction tx = Db.beginTx())
            {
                for (int i = 0; i < drops; i++)
                {
                    indexesToDrop.Add(Db.schema().indexFor(Label(i)).on(KEY).create());
                }
                tx.Success();
            }

            // WHEN dropping them
            Race          race = new Race();
            ISet <string> expectedIndexedLabels = new HashSet <string>();

            for (int i = 0; i < creates; i++)
            {
                expectedIndexedLabels.Add(Label(drops + i).name());
                race.AddContestant(IndexCreate(drops + i), 1);
            }
            foreach (IndexDefinition index in indexesToDrop)
            {
                race.AddContestant(IndexDrop(index), 1);
            }
            race.Go();

            // THEN they should all be observed as dropped in the end
            using (Transaction tx = Db.beginTx())
            {
                IList <IndexDefinition> indexes = new IList <IndexDefinition> {
                    Db.schema().Indexes
                };
                assertEquals(creates, indexes.Count);
                tx.Success();

                foreach (IndexDefinition index in indexes)
                {
                    assertTrue(expectedIndexedLabels.remove(single(index.Labels).name()));
                }
            }
        }
예제 #12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldHandleTheWholeWorkloadShebang() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldHandleTheWholeWorkloadShebang()
        {
            // GIVEN
            const int         size       = 1_000;
            const long        bufferTime = 3;
            VerifyingConsumer consumer   = new VerifyingConsumer(size);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.time.Clock clock = org.neo4j.time.Clocks.systemClock();
            Clock clock = Clocks.systemClock();

            System.Func <long>      chunkThreshold = clock.millis;
            System.Predicate <long> safeThreshold  = time => clock.millis() - bufferTime >= time;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final DelayedBuffer<long> buffer = new DelayedBuffer<>(chunkThreshold, safeThreshold, 10, consumer);
            DelayedBuffer <long> buffer      = new DelayedBuffer <long>(chunkThreshold, safeThreshold, 10, consumer);
            MaintenanceThread    maintenance = new MaintenanceThread(buffer, 5);
            Race      adders         = new Race();
            const int numberOfAdders = 20;

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final byte[] offeredIds = new byte[size];
            sbyte[] offeredIds = new sbyte[size];
            for (int i = 0; i < numberOfAdders; i++)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int finalI = i;
                int finalI = i;
                adders.AddContestant(() =>
                {
                    for (int j = 0; j < size; j++)
                    {
                        if (j % numberOfAdders == finalI)
                        {
                            buffer.Offer(j);
                            offeredIds[j] = 1;
                            parkNanos(MILLISECONDS.toNanos(current().Next(2)));
                        }
                    }
                });
            }

            // WHEN (multi-threaded) offering of ids
            adders.Go();
            // ... ensuring the test is sane itself (did we really offer all these IDs?)
            for (int i = 0; i < size; i++)
            {
                assertEquals("ID " + i, ( sbyte )1, offeredIds[i]);
            }
            maintenance.Halt();
            buffer.Close();

            // THEN
            consumer.AssertHaveOnlySeenRange(0, size - 1);
        }
        /*
         * There was an issue where if multiple concurrent appending threads did append and they moved on
         * to await a force, where the force would fail and the one doing the force would raise a panic...
         * the other threads may not notice the panic and move on to mark those transactions as committed
         * and notice the panic later (which would be too late).
         */
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldHaveAllConcurrentAppendersSeePanic() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldHaveAllConcurrentAppendersSeePanic()
        {
            // GIVEN
            Adversary adversary = new ClassGuardedAdversary(new CountingAdversary(1, true), FailMethod(typeof(BatchingTransactionAppender), "force"));
            EphemeralFileSystemAbstraction efs = new EphemeralFileSystemAbstraction();
            FileSystemAbstraction          fs  = new AdversarialFileSystemAbstraction(adversary, efs);

            _life.add(new FileSystemLifecycleAdapter(fs));
            DatabaseHealth databaseHealth = new DatabaseHealth(mock(typeof(DatabasePanicEventGenerator)), NullLog.Instance);
            LogFiles       logFiles       = LogFilesBuilder.builder(_testDirectory.databaseLayout(), fs).withLogVersionRepository(_logVersionRepository).withTransactionIdStore(_transactionIdStore).build();

            _life.add(logFiles);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final BatchingTransactionAppender appender = life.add(new BatchingTransactionAppender(logFiles, logRotation, transactionMetadataCache, transactionIdStore, explicitIndexTransactionOrdering, databaseHealth));
            BatchingTransactionAppender appender = _life.add(new BatchingTransactionAppender(logFiles, _logRotation, _transactionMetadataCache, _transactionIdStore, _explicitIndexTransactionOrdering, databaseHealth));

            _life.start();

            // WHEN
            int numberOfAppenders = 10;

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch trap = new java.util.concurrent.CountDownLatch(numberOfAppenders);
            System.Threading.CountdownEvent trap = new System.Threading.CountdownEvent(numberOfAppenders);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.impl.transaction.tracing.LogAppendEvent beforeForceTrappingEvent = new org.neo4j.kernel.impl.transaction.tracing.LogAppendEvent_Empty()
            LogAppendEvent beforeForceTrappingEvent = new LogAppendEvent_EmptyAnonymousInnerClass(this, trap);
            Race           race = new Race();

            for (int i = 0; i < numberOfAppenders; i++)
            {
                race.AddContestant(() =>
                {
                    try
                    {
                        // Append to the log, the LogAppenderEvent will have all of the appending threads
                        // do wait for all of the other threads to start the force thing
                        appender.Append(Tx(), beforeForceTrappingEvent);
                        fail("No transaction should be considered appended");
                    }
                    catch (IOException)
                    {
                        // Good, we know that this test uses an adversarial file system which will throw
                        // an exception in BatchingTransactionAppender#force, and since all these transactions
                        // will append and be forced in the same batch, where the force will fail then
                        // all these transactions should fail. If there's any transaction not failing then
                        // it just didn't notice the panic, which would be potentially hazardous.
                    }
                });
            }

            // THEN perform the race. The relevant assertions are made inside the contestants.
            race.Go();
        }
예제 #14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertBothSucceeds(Runnable lockAction1, Runnable lockAction2) throws Throwable
        private void AssertBothSucceeds(ThreadStart lockAction1, ThreadStart lockAction2)
        {
            AssertUU();
            Race           race = new Race();
            LockContestant c1   = new LockContestant(lockAction1);
            LockContestant c2   = new LockContestant(lockAction2);

            // when
            race.AddContestant(c1);
            race.AddContestant(c2);

            race.Go();

            // then
            Pair <bool, bool> c1State = c1.State();
            Pair <bool, bool> c2State = c2.State();

            assertTrue(WithState("Expected both to acquire lock.", c1State, c2State), c1State.First() && c2State.First());
            assertTrue(WithState("Expected both to be started.", c1State, c2State), c1State.Other() && c2State.Other());
        }
예제 #15
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void stressInstantiationWithClose() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void StressInstantiationWithClose()
        {
            // given
            StringFactory factory             = new StringFactory();
            TemporalIndexCache <string> cache = new TemporalIndexCache <string>(factory);
            Race       race = (new Race()).withRandomStartDelays();
            MutableInt instantiatedAtClose = new MutableInt();

            race.AddContestant(() =>
            {
                try
                {
                    cache.UncheckedSelect(_valueGroups[0]);
                    cache.UncheckedSelect(_valueGroups[1]);
                }
                catch (System.InvalidOperationException)
                {
                    // This exception is OK since it may have been closed
                }
            }, 1);
            race.AddContestant(() =>
            {
                cache.CloseInstantiateCloseLock();
                instantiatedAtClose.Value = count(cache);
            }, 1);

            // when
            race.Go();

            // then
            try
            {
                cache.UncheckedSelect(_valueGroups[2]);
                fail("No instantiation after closed");
            }
            catch (System.InvalidOperationException)
            {
                // good
            }
            assertEquals(instantiatedAtClose.intValue(), count(cache));
        }
예제 #16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void slavesTerminateOrReadConsistentDataWhenApplyingBatchLargerThanSafeZone() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SlavesTerminateOrReadConsistentDataWhenApplyingBatchLargerThanSafeZone()
        {
            long safeZone = TimeUnit.MILLISECONDS.toSeconds(0);

            ClusterRule.withSharedSetting(HaSettings.id_reuse_safe_zone_time, safeZone.ToString());
            // given
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.impl.ha.ClusterManager.ManagedCluster cluster = clusterRule.startCluster();
            ClusterManager.ManagedCluster cluster = ClusterRule.startCluster();
            HighlyAvailableGraphDatabase  master  = cluster.Master;

            // when
            // ... slaves and master has node with long string property
            long entityId = Action.createInitialEntity(master);

            cluster.Sync();
            // ... and property is removed on master
            Action.removeProperties(master, entityId);
            Thread.Sleep(100);
            // ... and maintenance is called to make sure "safe" ids are freed to be reused
            ForceMaintenance(master);
            // ... and a new property is created on master that
            Action.setNewProperties(master, entityId);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.ha.HighlyAvailableGraphDatabase slave = cluster.getAnySlave();
            HighlyAvailableGraphDatabase slave = cluster.AnySlave;
            Race race = new Race();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean end = new java.util.concurrent.atomic.AtomicBoolean(false);
            AtomicBoolean end = new AtomicBoolean(false);

            for (int i = 0; i < READER_CONTESTANTS; i++)
            {
                race.AddContestant(ReadContestant(Action, entityId, slave, end));
            }

            race.AddContestant(PullUpdatesContestant(slave, end));

            race.Go();
        }
예제 #17
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldSynchronizeModifications() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldSynchronizeModifications()
        {
            // given
            IndexMapReference @ref = new IndexMapReference();

            IndexProxy[] existing = MockedIndexProxies(5, 0);
            @ref.Modify(indexMap =>
            {
                for (int i = 0; i < existing.Length; i++)
                {
                    indexMap.putIndexProxy(existing[i]);
                }
                return(indexMap);
            });

            // when
            Race race = new Race();

            for (int i = 0; i < existing.Length; i++)
            {
                race.AddContestant(RemoveIndexProxy(@ref, i), 1);
            }
            IndexProxy[] created = MockedIndexProxies(3, existing.Length);
            for (int i = 0; i < existing.Length; i++)
            {
                race.AddContestant(PutIndexProxy(@ref, created[i]), 1);
            }
            race.Go();

            // then
            for (int i = 0; i < existing.Length; i++)
            {
                assertNull(@ref.getIndexProxy(i));
            }
            for (int i = 0; i < created.Length; i++)
            {
                assertSame(created[i], @ref.getIndexProxy(existing.Length + i));
            }
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void runTwoThreads(System.Action<TestKernelTransaction> thread1Action, System.Action<TestKernelTransaction> thread2Action) throws Throwable
        private void RunTwoThreads(System.Action <TestKernelTransaction> thread1Action, System.Action <TestKernelTransaction> thread2Action)
        {
            TestKernelTransaction tx      = TestKernelTransaction.Create().initialize();
            AtomicLong            t1Count = new AtomicLong();
            AtomicLong            t2Count = new AtomicLong();
            long endTime = currentTimeMillis() + TEST_RUN_TIME_MS;
            int  limit   = 20_000;

            Race race = new Race();

            race.WithEndCondition(() => ((t1Count.get() >= limit) && (t2Count.get() >= limit)) || (currentTimeMillis() >= endTime));
            race.AddContestant(() =>
            {
                thread1Action(tx);
                t1Count.incrementAndGet();
            });
            race.AddContestant(() =>
            {
                thread2Action(tx);
                t2Count.incrementAndGet();
            });
            race.Go();
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldKeepTransactionsIntactWhenConcurrentlyRotationAndAppending() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldKeepTransactionsIntactWhenConcurrentlyRotationAndAppending()
        {
            // GIVEN
            LogVersionRepository logVersionRepository = new SimpleLogVersionRepository();
            LogFiles             logFiles             = LogFilesBuilder.builder(_directory.databaseLayout(), _fileSystemRule.get()).withLogVersionRepository(logVersionRepository).withRotationThreshold(ByteUnit.mebiBytes(1)).withTransactionIdStore(new SimpleTransactionIdStore()).build();

            _life.add(logFiles);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean end = new java.util.concurrent.atomic.AtomicBoolean();
            AtomicBoolean            end           = new AtomicBoolean();
            AllTheMonitoring         monitoring    = new AllTheMonitoring(end, 100);
            TransactionIdStore       txIdStore     = new SimpleTransactionIdStore();
            TransactionMetadataCache metadataCache = new TransactionMetadataCache();

            monitoring.LogFile = logFiles.LogFile;
            DatabaseHealth health   = new DatabaseHealth(mock(typeof(DatabasePanicEventGenerator)), NullLog.Instance);
            LogRotation    rotation = new LogRotationImpl(monitoring, logFiles, health);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final TransactionAppender appender = life.add(new BatchingTransactionAppender(logFiles, rotation, metadataCache, txIdStore, BYPASS, health));
            TransactionAppender appender = _life.add(new BatchingTransactionAppender(logFiles, rotation, metadataCache, txIdStore, BYPASS, health));

            // WHEN
            Race race = new Race();

            for (int i = 0; i < 10; i++)
            {
                race.AddContestant(() =>
                {
                    while (!end.get())
                    {
                        try
                        {
                            appender.Append(new TransactionToApply(SillyTransaction(1_000)), NULL);
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace(System.out);
                            end.set(true);
                            fail(e.Message);
                        }
                    }
                });
            }
            race.AddContestant(EndAfterMax(10, SECONDS, end));
            race.Go();

            // THEN
            assertTrue(monitoring.NumberOfRotations() > 0);
        }
예제 #20
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertOnlyOneSucceeds(Runnable lockAction1, Runnable lockAction2) throws Throwable
        private void AssertOnlyOneSucceeds(ThreadStart lockAction1, ThreadStart lockAction2)
        {
            AssertUU();
            Race           race = new Race();
            LockContestant c1   = new LockContestant(lockAction1);
            LockContestant c2   = new LockContestant(lockAction2);

            // when
            race.AddContestant(c1);
            race.AddContestant(c2);

            race.GoAsync();
            while (!(c1.LockAcquired() || c2.LockAcquired()) || !(c1.Started() && c2.Started()))
            {
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
            }

            // then
            Pair <bool, bool> c1State = c1.State();
            Pair <bool, bool> c2State = c2.State();

            assertNotEquals(WithState("Expected exactly one to acquire lock.", c1State, c2State), c1State.First(), c2State.First());
            assertTrue(WithState("Expected both to be started.", c1State, c2State), c1State.Other() && c2State.Other());
        }
예제 #21
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void doRace(System.Func<NumberArray,int,Runnable> contestantCreator) throws Throwable
        private void DoRace(System.Func <NumberArray, int, ThreadStart> contestantCreator)
        {
            PageCache pageCache = _pageCacheRule.getPageCache(_fs);
            PagedFile file      = pageCache.Map(_dir.file("file"), pageCache.PageSize(), CREATE, DELETE_ON_CLOSE);
            Race      race      = new Race();

            using (NumberArray array = GetNumberArray(file))
            {
                for (int i = 0; i < CONTESTANTS; i++)
                {
                    race.AddContestant(contestantCreator(array, i));
                }
                race.Go();
            }
        }
예제 #22
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void raceEncode(String[] INPUT, System.Func<org.neo4j.values.storable.Value, String> encodeFunction) throws Throwable
        private void RaceEncode(string[] input, System.Func <Value, string> encodeFunction)
        {
            Race race = new Race();

            foreach (string input in input)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.values.storable.Value inputValue = org.neo4j.values.storable.Values.of(new String[]{input});
                Value inputValue = Values.of(new string[] { input });
                race.AddContestant(() =>
                {
                    string first = encodeFunction(inputValue);
                    for (int i = 0; i < 1000; i++)
                    {
                        string encoded = encodeFunction(inputValue);
                        assertEquals("Each attempt at encoding should yield the same result. Turns out that first one was '" + first + "', yet another one was '" + encoded + "'", first, encoded);
                    }
                });
            }
            race.Go();
        }
예제 #23
0
        /// <summary>
        /// The test case is basically loads of concurrent CREATE/DELETE NODE or sometimes just CREATE, keeping the created node in an array
        /// for dedicated deleter threads to pick up and delete as fast as they can see them. This concurrently with large creation transactions.
        /// </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldStressIt() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldStressIt()
        {
            // given
            Race race = (new Race()).withMaxDuration(5, TimeUnit.SECONDS);
            AtomicReferenceArray <Node> nodeHeads = new AtomicReferenceArray <Node>(_numberOfCreators);

            for (int i = 0; i < _numberOfCreators; i++)
            {
                race.AddContestant(Creator(nodeHeads, i));
            }
            race.AddContestants(NUMBER_OF_DELETORS, Deleter(nodeHeads));

            // when
            race.Go();

            // then
            DatabaseLayout dbLayout = Db.databaseLayout();

            Db.shutdownAndKeepStore();
            assertTrue((new ConsistencyCheckService()).runFullConsistencyCheck(dbLayout, defaults(), NONE, toOutputStream(System.out), false, new ConsistencyFlags(true, true, true, true, false)).Successful);
        }
예제 #24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldSumCounts() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldSumCounts()
        {
            // given
            DataStatistics stats = new DataStatistics(1, 2, new RelationshipTypeCount[0]);
            Race           race  = new Race();
            int            types = 10;

            long[] expected = new long[types];
            int    threads  = Runtime.Runtime.availableProcessors();

            for (int i = 0; i < threads; i++)
            {
                long[] local = new long[types];
                for (int j = 0; j < types; j++)
                {
                    local[j]     = Random.Next(1_000, 2_000);
                    expected[j] += local[j];
                }
                race.AddContestant(() =>
                {
                    using (DataStatistics.Client client = stats.NewClient())
                    {
                        for (int typeId = 0; typeId < types; typeId++)
                        {
                            while (local[typeId]-- > 0)
                            {
                                client.Increment(typeId);
                            }
                        }
                    }
                });
            }

            // when
            race.Go();

            // then
            stats.forEach(count => assertEquals(expected[count.TypeId], count.Count));
        }
예제 #25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void concurrentSchemaRuleAdd() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConcurrentSchemaRuleAdd()
        {
            SchemaCache cache       = NewSchemaCache();
            Race        race        = new Race();
            int         indexNumber = 10;

            for (int i = 0; i < indexNumber; i++)
            {
                int id = i;
                race.AddContestant(() => cache.addSchemaRule(NewIndexRule(id, id, id)));
            }
            race.Go();

            assertEquals(indexNumber, Iterables.count(cache.IndexDescriptors()));
            for (int labelId = 0; labelId < indexNumber; labelId++)
            {
                assertEquals(1, Iterators.count(cache.IndexDescriptorsForLabel(labelId)));
            }
            for (int propertyId = 0; propertyId < indexNumber; propertyId++)
            {
                assertEquals(1, Iterators.count(cache.IndexesByProperty(propertyId)));
            }
        }
예제 #26
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldKeepItsCoolWhenMultipleThreadsAreHammeringIt() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldKeepItsCoolWhenMultipleThreadsAreHammeringIt()
        {
            // An interesting note is that during tests the call to sequence#offer made no difference
            // in performance, so there seems to be no visible penalty in using ArrayQueueOutOfOrderSequence.

            // GIVEN a sequence with intentionally low starting queue size
            System.Func <long, long[]> metaFunction = number => new long[] { number + 2, number * 2 };
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicLong numberSource = new java.util.concurrent.atomic.AtomicLong();
            AtomicLong numberSource = new AtomicLong();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.impl.util.OutOfOrderSequence sequence = new org.neo4j.kernel.impl.util.ArrayQueueOutOfOrderSequence(numberSource.get(), 5, metaFunction.apply(numberSource.get()));
            OutOfOrderSequence sequence = new ArrayQueueOutOfOrderSequence(numberSource.get(), 5, metaFunction(numberSource.get()));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.Race race = new org.neo4j.test.Race().withEndCondition(() -> numberSource.get() > 10_000_000);
            Race race         = (new Race()).withEndCondition(() => numberSource.get() > 10_000_000);
            int  offerThreads = max(2, Runtime.Runtime.availableProcessors() - 1);

            race.AddContestants(offerThreads, () =>
            {
                long number = numberSource.incrementAndGet();
                sequence.Offer(number, metaFunction(number));
            });
            ThreadStart verifier = () =>
            {
                long[] highest      = sequence.Get();
                long[] expectedMeta = metaFunction(highest[0]);
                assertArrayEquals(expectedMeta, copyOfRange(highest, 1, highest.Length));
            };

            race.AddContestant(verifier);
            race.Go();

            // THEN
            verifier.run();
        }
예제 #27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBeAbleToSnapshotDuringHeavyLoad() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBeAbleToSnapshotDuringHeavyLoad()
        {
            // GIVEN
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final KernelTransactions transactions = newKernelTransactions();
            KernelTransactions transactions = NewKernelTransactions();
            Race      race    = new Race();
            const int threads = 50;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean end = new java.util.concurrent.atomic.AtomicBoolean();
            AtomicBoolean end = new AtomicBoolean();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReferenceArray<KernelTransactionsSnapshot> snapshots = new java.util.concurrent.atomic.AtomicReferenceArray<>(threads);
            AtomicReferenceArray <KernelTransactionsSnapshot> snapshots = new AtomicReferenceArray <KernelTransactionsSnapshot>(threads);

            // Representing "transaction" threads
            for (int i = 0; i < threads; i++)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int threadIndex = i;
                int threadIndex = i;
                race.AddContestant(() =>
                {
                    ThreadLocalRandom random = ThreadLocalRandom.current();
                    while (!end.get())
                    {
                        try
                        {
                            using (KernelTransaction transaction = GetKernelTransaction(transactions))
                            {
                                KernelTransactionsSnapshot snapshot = null;
                                try
                                {
                                    parkNanos(MILLISECONDS.toNanos(random.Next(3)));
                                    if (snapshots.get(threadIndex) == null)
                                    {
                                        requireNonNull(transactions, "transactions is null");
                                        snapshot = requireNonNull(transactions.Get(), "transactions.get() returned null");
                                        snapshots.set(threadIndex, snapshot);
                                        parkNanos(MILLISECONDS.toNanos(random.Next(3)));
                                    }
                                }
                                catch (Exception e)
                                {
                                    StringBuilder sb = (new StringBuilder("Gotcha!\n")).Append("threadIndex=").Append(threadIndex).Append('\n').Append("transaction=").Append(transaction).Append('\n').Append("snapshots=").Append(snapshots).Append('\n').Append("snapshot=").Append(snapshot).Append('\n').Append("end=").Append(end);
                                    throw new Exception(sb.ToString(), e);
                                }
                            }
                        }
                        catch (TransactionFailureException e)
                        {
                            throw new Exception(e);
                        }
                    }
                });
            }

            // Just checks snapshots
            race.AddContestant(() =>
            {
                ThreadLocalRandom random = ThreadLocalRandom.current();
                int snapshotsLeft        = 1_000;
                while (snapshotsLeft > 0)
                {
                    int threadIndex = random.Next(threads);
                    KernelTransactionsSnapshot snapshot = snapshots.get(threadIndex);
                    if (snapshot != null && snapshot.AllClosed())
                    {
                        snapshotsLeft--;
                        snapshots.set(threadIndex, null);
                    }
                }

                // End condition of this test can be described as:
                //   when 1000 snapshots have been seen as closed.
                // setting this boolean to true will have all other threads end as well so that race.go() will end
                end.set(true);
            });

            // WHEN
            race.Go();
        }