Ejemplo n.º 1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void nestedTransactionCanAcquireLocksFromTransactionObject() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void NestedTransactionCanAcquireLocksFromTransactionObject()
        {
            // given
            Node resource = CreateNode();

            using (Transaction outerTx = _db.beginTx(), Transaction nestedTx = _db.beginTx())
            {
                assertNotSame(outerTx, nestedTx);

                using (OtherThreadExecutor <Void> otherThread = new OtherThreadExecutor <Void>("other thread", null))
                {
                    // when
                    Lock          @lock  = nestedTx.AcquireWriteLock(resource);
                    Future <Lock> future = TryToAcquireSameLockOnAnotherThread(resource, otherThread);

                    // then
                    AcquireOnOtherThreadTimesOut(future);

                    // and when
                    @lock.Release();

                    //then
                    assertNotNull(future.get());
                }
            }
        }
Ejemplo n.º 2
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private java.util.concurrent.Future<org.neo4j.graphdb.Lock> tryToAcquireSameLockOnAnotherThread(org.neo4j.graphdb.Node resource, org.neo4j.test.OtherThreadExecutor<Void> otherThread) throws Exception
        private Future <Lock> TryToAcquireSameLockOnAnotherThread(Node resource, OtherThreadExecutor <Void> otherThread)
        {
            Future <Lock> future = otherThread.ExecuteDontWait(AcquireWriteLock(resource));

            otherThread.WaitUntilWaiting();
            return(future);
        }
Ejemplo n.º 3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBeAbleToCancelPopulationJob() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBeAbleToCancelPopulationJob()
        {
            // GIVEN
            CreateNode(map(_name, "Mattias"), _first);
            IndexPopulator      populator = mock(typeof(IndexPopulator));
            FlippableIndexProxy index     = mock(typeof(FlippableIndexProxy));
            IndexStoreView      storeView = mock(typeof(IndexStoreView));
            ControlledStoreScan storeScan = new ControlledStoreScan();

            when(storeView.VisitNodes(any(typeof(int[])), any(typeof(System.Func <int, bool>)), ArgumentMatchers.any(), ArgumentMatchers.any <Visitor <NodeLabelUpdate, Exception> >(), anyBoolean())).thenReturn(storeScan);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexPopulationJob job = newIndexPopulationJob(populator, index, storeView, org.neo4j.logging.NullLogProvider.getInstance(), org.neo4j.storageengine.api.EntityType.NODE, indexDescriptor(FIRST, name, false));
            IndexPopulationJob job = NewIndexPopulationJob(populator, index, storeView, NullLogProvider.Instance, EntityType.NODE, IndexDescriptor(_first, _name, false));

            OtherThreadExecutor <Void> populationJobRunner = Cleanup.add(new OtherThreadExecutor <Void>("Population job test runner", null));
            Future <Void> runFuture = populationJobRunner.ExecuteDontWait(state =>
            {
                job.Run();
                return(null);
            });

            storeScan.Latch.waitForAllToStart();
            job.Cancel().get();
            storeScan.Latch.waitForAllToFinish();

            // WHEN
            runFuture.get();

            // THEN
            verify(populator, times(1)).close(false);
            verify(index, never()).flip(any(), any());
        }
Ejemplo n.º 4
0
        // Timeout as fallback safety if test deadlocks
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 60_000) public void shouldWaitOnStopUntilTheRunningCheckpointIsDone() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldWaitOnStopUntilTheRunningCheckpointIsDone()
        {
            // given
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<Throwable> ex = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <Exception> ex = new AtomicReference <Exception>();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean stoppedCompleted = new java.util.concurrent.atomic.AtomicBoolean();
            AtomicBoolean stoppedCompleted = new AtomicBoolean();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch checkPointerLatch = new org.neo4j.test.DoubleLatch(1);
            DoubleLatch checkPointerLatch = new DoubleLatch(1);
            OtherThreadExecutor <Void> otherThreadExecutor = new OtherThreadExecutor <Void>("scheduler stopper", null);
            CheckPointer checkPointer = new CheckPointerAnonymousInnerClass(this, checkPointerLatch);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final CheckPointScheduler scheduler = new CheckPointScheduler(checkPointer, ioLimiter, jobScheduler, 20L, health);
            CheckPointScheduler scheduler = new CheckPointScheduler(checkPointer, _ioLimiter, _jobScheduler, 20L, _health);

            // when
            scheduler.Start();

            Thread runCheckPointer = new Thread(_jobScheduler.runJob);

            runCheckPointer.Start();

            checkPointerLatch.WaitForAllToStart();

            otherThreadExecutor.ExecuteDontWait((OtherThreadExecutor.WorkerCommand <Void, Void>)state =>
            {
                try
                {
                    scheduler.Stop();
                    stoppedCompleted.set(true);
                }
                catch (Exception throwable)
                {
                    ex.set(throwable);
                }
                return(null);
            });
            otherThreadExecutor.WaitUntilWaiting(details => details.isAt(typeof(CheckPointScheduler), "waitOngoingCheckpointCompletion"));

            // then
            assertFalse(stoppedCompleted.get());

            checkPointerLatch.Finish();
            runCheckPointer.Join();

            while (!stoppedCompleted.get())
            {
                Thread.Sleep(1);
            }
            otherThreadExecutor.Dispose();

            assertNull(ex.get());
        }
Ejemplo n.º 5
0
        public override string ToString()
        {
            OtherThreadExecutor <STATE> otherThread = _executor;

            if (otherThread == null)
            {
                return("OtherThreadRule[state=dead]");
            }
            return(otherThread.ToString());
        }
Ejemplo n.º 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBlockAccessDuringFlipAndThenDelegateToCorrectContext() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBlockAccessDuringFlipAndThenDelegateToCorrectContext()
        {
            // GIVEN
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexProxy contextBeforeFlip = mockIndexProxy();
            IndexProxy contextBeforeFlip = mockIndexProxy();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexProxy contextAfterFlip = mockIndexProxy();
            IndexProxy contextAfterFlip = mockIndexProxy();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final FlippableIndexProxy flippable = new FlippableIndexProxy(contextBeforeFlip);
            FlippableIndexProxy flippable = new FlippableIndexProxy(contextBeforeFlip);

            flippable.FlipTarget = SingleProxy(contextAfterFlip);

            // And given complicated thread race condition tools
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch triggerFinishFlip = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent triggerFinishFlip = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch triggerExternalAccess = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent triggerExternalAccess = new System.Threading.CountdownEvent(1);

            OtherThreadExecutor <Void> flippingThread  = Cleanup.add(new OtherThreadExecutor <Void>("Flipping thread", null));
            OtherThreadExecutor <Void> dropIndexThread = Cleanup.add(new OtherThreadExecutor <Void>("Drop index thread", null));

            // WHEN one thread starts flipping to another context
            Future <Void> flipContextFuture = flippingThread.ExecuteDontWait(StartFlipAndWaitForLatchBeforeFinishing(flippable, triggerFinishFlip, triggerExternalAccess));

            // And I wait until the flipping thread is in the middle of "the flip"
            assertTrue(triggerExternalAccess.await(10, SECONDS));

            // And another thread comes along and drops the index
            Future <Void> dropIndexFuture = dropIndexThread.ExecuteDontWait(DropTheIndex(flippable));

            dropIndexThread.WaitUntilWaiting();

            // And the flipping thread finishes the flip
            triggerFinishFlip.Signal();

            // And both threads get to finish up and return
            dropIndexFuture.get(10, SECONDS);
            flipContextFuture.get(10, SECONDS);

            // THEN the thread wanting to drop the index should not have interacted with the original context
            // eg. it should have waited for the flip to finish
            verifyNoMoreInteractions(contextBeforeFlip);

            // But it should have gotten to drop the new index context, after the flip happened.
            verify(contextAfterFlip).drop();
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldHaveOneThreadWaitForARemoval() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldHaveOneThreadWaitForARemoval()
        {
            // GIVEN
            IdOrderingQueue queue = new SynchronizedArrayIdOrderingQueue(5);

            queue.Offer(3);
            queue.Offer(5);

            // WHEN another thread comes in and awaits 5
            OtherThreadExecutor <Void> t2     = Cleanup.add(new OtherThreadExecutor <Void>("T2", null));
            Future <object>            await5 = t2.ExecuteDontWait(AwaitHead(queue, 5));

            t2.WaitUntilWaiting();
            // ... and head (3) gets removed
            queue.RemoveChecked(3);

            // THEN the other thread should be OK to continue
            await5.get();
        }
Ejemplo n.º 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void put_if_absent_works_across_instances() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void PutIfAbsentWorksAcrossInstances()
        {
            // GIVEN
            // -- two instances, each begin a transaction
            string key   = "key2";
            string value = "value2";
            HighlyAvailableGraphDatabase db1 = Cluster.Master;
            HighlyAvailableGraphDatabase db2 = Cluster.AnySlave;
            long node = CreateNode(db1, key, value, false);

            Cluster.sync();
            OtherThreadExecutor <HighlyAvailableGraphDatabase> w1 = new OtherThreadExecutor <HighlyAvailableGraphDatabase>("w1", db1);
            OtherThreadExecutor <HighlyAvailableGraphDatabase> w2 = new OtherThreadExecutor <HighlyAvailableGraphDatabase>("w2", db2);
            Transaction tx1 = w1.Execute(new BeginTx());
            Transaction tx2 = w2.Execute(new BeginTx());

            // WHEN
            // -- second instance does putIfAbsent --> null
            assertNull(w2.Execute(new PutIfAbsent(node, key, value)));
            // -- get a future to first instance putIfAbsent. Wait for it to go and await the lock
            Future <Node> w1Future = w1.ExecuteDontWait(new PutIfAbsent(node, key, value));

            w1.WaitUntilWaiting();
            // -- second instance completes tx
            w2.Execute(new FinishTx(tx2, true));
            tx2.Success();
            tx2.Close();

            // THEN
            // -- first instance can complete the future with a non-null result
            assertNotNull(w1Future.get());
            w1.Execute(new FinishTx(tx1, true));
            // -- assert the index has got one entry and both instances have the same data
            AssertNodeAndIndexingExists(db1, node, key, value);
            AssertNodeAndIndexingExists(db2, node, key, value);
            Cluster.sync();
            AssertNodeAndIndexingExists(Cluster.getAnySlave(db1, db2), node, key, value);

            w2.Dispose();
            w1.Dispose();
        }
Ejemplo n.º 9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAbortStoreScanWaitOnDrop() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAbortStoreScanWaitOnDrop()
        {
            // given the proxy structure
            FakePopulatingIndexProxy   @delegate = new FakePopulatingIndexProxy();
            FlippableIndexProxy        flipper   = new FlippableIndexProxy(@delegate);
            OtherThreadExecutor <Void> waiter    = Cleanup.add(new OtherThreadExecutor <Void>("Waiter", null));

            // and a thread stuck in the awaitStoreScanCompletion loop
            Future <object> waiting = waiter.ExecuteDontWait(state => flipper.AwaitStoreScanCompleted(0, MILLISECONDS));

            while ([email protected])
            {
                Thread.Sleep(10);
            }

            // when
            flipper.Drop();

            // then the waiting should quickly be over
            waiting.get(10, SECONDS);
        }
Ejemplo n.º 10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldApplyBackPressure() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldApplyBackPressure()
        {
            // given
            int backPressureThreshold = 10;
            BlockableMonitor monitor  = new BlockableMonitor();

            using (OtherThreadExecutor <Void> t2 = new OtherThreadExecutor <Void>("T2", null), BadCollector badCollector = new BadCollector(NULL_OUTPUT_STREAM, UNLIMITED_TOLERANCE, COLLECT_ALL, backPressureThreshold, false, monitor))
            {
                for (int i = 0; i < backPressureThreshold; i++)
                {
                    badCollector.CollectDuplicateNode(i, i, "group");
                }

                // when
                Future <object> enqueue = t2.ExecuteDontWait(command(() => badCollector.collectDuplicateNode(999, 999, "group")));
                t2.WaitUntilWaiting(waitDetails => waitDetails.isAt(typeof(BadCollector), "collect"));
                monitor.Unblock();

                // then
                enqueue.get();
            }
        }
Ejemplo n.º 11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldReleaseSearcherProperlyAfterVerifyingDeferredConstraints() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldReleaseSearcherProperlyAfterVerifyingDeferredConstraints()
        {
            // given
            _populator = NewPopulator();

            /*
             * This test was created due to a problem in closing an index updater after deferred constraints
             * had been verified, where it got stuck in a busy loop in ReferenceManager#acquire.
             */

            // GIVEN an index updater that we close
            OtherThreadExecutor <Void> executor = _cleanup.add(new OtherThreadExecutor <Void>("Deferred", null));

            executor.Execute((OtherThreadExecutor.WorkerCommand <Void, Void>)state =>
            {
                using (IndexUpdater updater = _populator.newPopulatingUpdater(_nodePropertyAccessor))
                {                 // Just open it and let it be closed
                }
                return(null);
            });
            // ... and where we verify deferred constraints after
            executor.Execute((OtherThreadExecutor.WorkerCommand <Void, Void>)state =>
            {
                _populator.verifyDeferredConstraints(_nodePropertyAccessor);
                return(null);
            });

            // WHEN doing more index updating after that
            // THEN it should be able to complete within a very reasonable time
            executor.Execute((OtherThreadExecutor.WorkerCommand <Void, Void>)state =>
            {
                using (IndexUpdater secondUpdater = _populator.newPopulatingUpdater(_nodePropertyAccessor))
                {                 // Just open it and let it be closed
                }
                return(null);
            }, 5, SECONDS);
        }
Ejemplo n.º 12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldLetShutdownCompleteInEventOfPanic() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldLetShutdownCompleteInEventOfPanic()
        {
            // GIVEN
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final TaskExecutor<Void> executor = new DynamicTaskExecutor<>(2, 0, 10, PARK, getClass().getSimpleName());
            TaskExecutor <Void> executor  = new DynamicTaskExecutor <Void>(2, 0, 10, _park, this.GetType().Name);
            IOException         exception = new IOException("Failure");

            // WHEN
            FailingTask failingTask = new FailingTask(exception);

            executor.Submit(failingTask);
            failingTask.Latch.await();

            // WHEN
            using (OtherThreadExecutor <Void> closer = new OtherThreadExecutor <Void>("closer", null))
            {
                Future <Void> shutdown = closer.ExecuteDontWait(state =>
                {
                    executor.Close();
                    return(null);
                });
                while (!closer.WaitUntilWaiting().isAt(typeof(DynamicTaskExecutor), "close"))
                {
                    Thread.Sleep(10);
                }

                // Here we've got a shutdown call stuck awaiting queue to be empty (since true was passed in)
                // at the same time we've got a FailingTask ready to throw its exception and another task
                // sitting in the queue after it. Now make the task throw that exception.
                failingTask.Latch.release();

                // Some time after throwing this, the shutdown request should have been completed.
                shutdown.get();
            }
        }
Ejemplo n.º 13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void concurrently_creating_same_property_key_in_different_transactions_should_end_up_with_same_key_id() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConcurrentlyCreatingSamePropertyKeyInDifferentTransactionsShouldEndUpWithSameKeyId()
        {
            // GIVEN
            GraphDatabaseAPI db = ( GraphDatabaseAPI )(new TestGraphDatabaseFactory()).newImpermanentDatabase();
            OtherThreadExecutor <WorkerState> worker1 = new OtherThreadExecutor <WorkerState>("w1", new WorkerState(db));
            OtherThreadExecutor <WorkerState> worker2 = new OtherThreadExecutor <WorkerState>("w2", new WorkerState(db));

            worker1.Execute(new BeginTx());
            worker2.Execute(new BeginTx());

            // WHEN
            string key = "mykey";

            worker1.Execute(new CreateNodeAndSetProperty(key));
            worker2.Execute(new CreateNodeAndSetProperty(key));
            worker1.Execute(new FinishTx());
            worker2.Execute(new FinishTx());
            worker1.Dispose();
            worker2.Dispose();

            // THEN
            assertEquals(1, PropertyKeyCount(db));
            Db.shutdown();
        }
Ejemplo n.º 14
0
 internal virtual void SetFuture <T1>(Future <T1> future, OtherThreadExecutor <Void> executor)
 {
     this.FutureConflict = future;
     this.Executor       = executor;
 }
Ejemplo n.º 15
0
 public static SyncOtherThreadOp <A> a <A>(
     OtherThreadExecutor <A> executor, Duration timeout
     ) => new SyncOtherThreadOp <A>(executor, timeout);
Ejemplo n.º 16
0
 public SyncOtherThreadOp(OtherThreadExecutor <A> executor, int timeoutMs = 1000)
 {
     this.executor  = executor;
     this.timeoutMs = timeoutMs;
 }
Ejemplo n.º 17
0
 public static SyncOtherThreadOp <A> a <A>(
     OtherThreadExecutor <A> executor
     ) => a(executor, 1.second());
Ejemplo n.º 18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void before()
        public virtual void Before()
        {
            _t1 = new OtherThreadExecutor <Void>("T1", null);
            _t2 = new OtherThreadExecutor <Void>("T2", null);
        }