Beispiel #1
0
        public virtual void AwaitUpdateApplication()
        {
            BinaryLatch updateLatch = new BinaryLatch();

            _scheduler.schedule(Group.INDEX_UPDATING, updateLatch.release);
            updateLatch.Await();
        }
Beispiel #2
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void verifyAsyncActionCausesConcurrentFlushingRush(org.neo4j.function.ThrowingConsumer<CheckPointerImpl,java.io.IOException> asyncAction) throws Exception
        private void VerifyAsyncActionCausesConcurrentFlushingRush(ThrowingConsumer <CheckPointerImpl, IOException> asyncAction)
        {
            AtomicLong  limitDisableCounter = new AtomicLong();
            AtomicLong  observedRushCount   = new AtomicLong();
            BinaryLatch backgroundCheckPointStartedLatch = new BinaryLatch();
            BinaryLatch forceCheckPointStartLatch        = new BinaryLatch();

            _limiter = new IOLimiterAnonymousInnerClass4(this, limitDisableCounter, forceCheckPointStartLatch);

            MockTxIdStore();
            CheckPointerImpl checkPointer = checkPointer();

            doAnswer(invocation =>
            {
                backgroundCheckPointStartedLatch.Release();
                forceCheckPointStartLatch.Await();
                long newValue = limitDisableCounter.get();
                observedRushCount.set(newValue);
                return(null);
            }).when(_storageEngine).flushAndForce(_limiter);

            Future <object> forceCheckPointer = forkFuture(() =>
            {
                backgroundCheckPointStartedLatch.Await();
                asyncAction.Accept(checkPointer);
                return(null);
            });

            when(_threshold.isCheckPointingNeeded(anyLong(), eq(_info))).thenReturn(true);
            checkPointer.CheckPointIfNeeded(_info);
            forceCheckPointer.get();
            assertThat(observedRushCount.get(), @is(1L));
        }
Beispiel #3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldReadYourOwnWrites() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldReadYourOwnWrites()
        {
            using (Transaction tx = Env.graph().beginTx())
            {
                Node node = Env.graph().createNode(Label.label("A"));
                node.SetProperty("prop", "one");
                tx.Success();
            }

            BinaryLatch latch = new BinaryLatch();

            long   dbVersion = Env.lastClosedTxId();
            Thread thread    = new Thread(() =>
            {
                try
                {
                    using (BoltStateMachine machine = Env.newMachine(_boltChannel))
                    {
                        machine.process(new InitMessage(USER_AGENT, emptyMap()), nullResponseHandler());
                        latch.Await();
                        machine.process(new RunMessage("MATCH (n:A) SET n.prop = 'two'", EMPTY_MAP), nullResponseHandler());
                        machine.process(PullAllMessage.INSTANCE, nullResponseHandler());
                    }
                }
                catch (BoltConnectionFatality connectionFatality)
                {
                    throw new Exception(connectionFatality);
                }
            });

            thread.Start();

            long dbVersionAfterWrite = dbVersion + 1;

            using (BoltStateMachine machine = Env.newMachine(_boltChannel))
            {
                BoltResponseRecorder recorder = new BoltResponseRecorder();
                machine.process(new InitMessage(USER_AGENT, emptyMap()), nullResponseHandler());
                latch.Release();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String bookmark = "neo4j:bookmark:v1:tx" + dbVersionAfterWrite;
                string bookmark = "neo4j:bookmark:v1:tx" + dbVersionAfterWrite;
                machine.process(new RunMessage("BEGIN", ValueUtils.asMapValue(singletonMap("bookmark", bookmark))), nullResponseHandler());
                machine.process(PullAllMessage.INSTANCE, recorder);
                machine.process(new RunMessage("MATCH (n:A) RETURN n.prop", EMPTY_MAP), nullResponseHandler());
                machine.process(PullAllMessage.INSTANCE, recorder);
                machine.process(new RunMessage("COMMIT", EMPTY_MAP), nullResponseHandler());
                machine.process(PullAllMessage.INSTANCE, recorder);

                assertThat(recorder.NextResponse(), succeeded());
                assertThat(recorder.NextResponse(), succeededWithRecord("two"));
                assertThat(recorder.NextResponse(), succeededWithMetadata("bookmark", _bookmarkPattern));
            }

            thread.Join();
        }
Beispiel #4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 30_000) public void terminatingTransactionMustEagerlyReleaseTheirLocks() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TerminatingTransactionMustEagerlyReleaseTheirLocks()
        {
            AtomicBoolean nodeLockAcquired = new AtomicBoolean();
            AtomicBoolean lockerDone       = new AtomicBoolean();
            BinaryLatch   lockerPause      = new BinaryLatch();
            long          nodeId;

            using (Transaction tx = Database.beginTx())
            {
                nodeId = Database.createNode().Id;
                tx.Success();
            }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> locker = executor.submit(() ->
            Future <object> locker = _executor.submit(() =>
            {
                using (Transaction tx = Database.beginTx())
                {
                    Node node = Database.getNodeById(nodeId);
                    tx.AcquireReadLock(node);
                    nodeLockAcquired.set(true);
                    lockerPause.Await();
                }
                lockerDone.set(true);
            });

            bool proceed;

            do
            {
                proceed = nodeLockAcquired.get();
            } while (!proceed);

            TerminateOngoingTransaction();

            assertFalse(lockerDone.get());                 // but the thread should still be blocked on the latch
            // Yet we should be able to proceed and grab the locks they once held
            using (Transaction tx = Database.beginTx())
            {
                // Write-locking is only possible if their shared lock was released
                tx.AcquireWriteLock(Database.getNodeById(nodeId));
                tx.Success();
            }
            // No exception from our lock client being stopped (e.g. we ended up blocked for too long) or from timeout
            lockerPause.Release();
            locker.get();
            assertTrue(lockerDone.get());
        }
Beispiel #5
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 30_000) public void shouldListAllLabelsInUseEvenWhenExclusiveLabelLocksAreTaken() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldListAllLabelsInUseEvenWhenExclusiveLabelLocksAreTaken()
        {
            // Given
            GraphDatabaseService db = DbRule.GraphDatabaseAPI;

            CreateNode(db, Labels.MyLabel);
            Node node = CreateNode(db, Labels.MyOtherLabel);

            using (Transaction tx = Db.beginTx())
            {
                node.Delete();
                tx.Success();
            }

            BinaryLatch indexCreateStarted       = new BinaryLatch();
            BinaryLatch indexCreateAllowToFinish = new BinaryLatch();
            Thread      indexCreator             = new Thread(() =>
            {
                using (Transaction tx = Db.beginTx())
                {
                    Db.schema().indexFor(Labels.MyLabel).on("prop").create();
                    indexCreateStarted.Release();
                    indexCreateAllowToFinish.Await();
                    tx.Success();
                }
            });

            indexCreator.Start();

            // When
            indexCreateStarted.Await();
            IList <Label> labels;

            using (Transaction ignored = Db.beginTx())
            {
                labels = new IList <Label> {
                    Db.AllLabelsInUse
                };
            }
            indexCreateAllowToFinish.Release();
            indexCreator.Join();

            // Then
            assertEquals(1, labels.Count);
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            assertThat(map(Label::name, labels), hasItems(Labels.MyLabel.name()));
        }
Beispiel #6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 30_000) public void shouldListAllRelationshipTypesInUseEvenWhenExclusiveRelationshipTypeLocksAreTaken() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldListAllRelationshipTypesInUseEvenWhenExclusiveRelationshipTypeLocksAreTaken()
        {
            // Given
            GraphDatabaseService db      = DbRule.GraphDatabaseAPI;
            RelationshipType     relType = RelationshipType.withName("REL");
            Node node = CreateNode(db, Labels.MyLabel);

            using (Transaction tx = Db.beginTx())
            {
                node.CreateRelationshipTo(node, relType).setProperty("prop", "val");
                tx.Success();
            }

            BinaryLatch indexCreateStarted       = new BinaryLatch();
            BinaryLatch indexCreateAllowToFinish = new BinaryLatch();
            Thread      indexCreator             = new Thread(() =>
            {
                using (Transaction tx = Db.beginTx())
                {
                    Db.execute("CALL db.index.fulltext.createRelationshipIndex('myIndex', ['REL'], ['prop'] )").close();
                    indexCreateStarted.Release();
                    indexCreateAllowToFinish.Await();
                    tx.Success();
                }
            });

            indexCreator.Start();

            // When
            indexCreateStarted.Await();
            IList <RelationshipType> relTypes;

            using (Transaction ignored = Db.beginTx())
            {
                relTypes = new IList <RelationshipType> {
                    Db.AllRelationshipTypesInUse
                };
            }
            indexCreateAllowToFinish.Release();
            indexCreator.Join();

            // Then
            assertEquals(1, relTypes.Count);
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            assertThat(map(RelationshipType::name, relTypes), hasItems(relType.Name()));
        }
Beispiel #7
0
        public virtual void Lock(int recordId)
        {
            int?        record  = recordId;
            BinaryLatch myLatch = new BinaryLatch();

            for ( ;;)
            {
                BinaryLatch existingLatch = _map.GetOrAdd(record, myLatch);
                if (existingLatch == null)
                {
                    break;
                }
                else
                {
                    existingLatch.Await();
                }
            }
        }
Beispiel #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void longRunningScheduledJobsMustNotDelayOtherLongRunningJobs()
        public virtual void LongRunningScheduledJobsMustNotDelayOtherLongRunningJobs()
        {
            _life.start();

            IList <JobHandle> handles        = new List <JobHandle>(30);
            AtomicLong        startedCounter = new AtomicLong();
            BinaryLatch       blockLatch     = new BinaryLatch();
            ThreadStart       task           = () =>
            {
                startedCounter.incrementAndGet();
                blockLatch.Await();
            };

            for (int i = 0; i < 10; i++)
            {
                handles.Add(_scheduler.schedule(Group.INDEX_POPULATION, task, 0, TimeUnit.MILLISECONDS));
            }
            for (int i = 0; i < 10; i++)
            {
                handles.Add(_scheduler.scheduleRecurring(Group.INDEX_POPULATION, task, int.MaxValue, TimeUnit.MILLISECONDS));
            }
            for (int i = 0; i < 10; i++)
            {
                handles.Add(_scheduler.scheduleRecurring(Group.INDEX_POPULATION, task, 0, int.MaxValue, TimeUnit.MILLISECONDS));
            }

            long deadline = TimeUnit.SECONDS.toNanos(10) + System.nanoTime();

            do
            {
                if (startedCounter.get() == handles.Count)
                {
                    // All jobs got started. We're good!
                    blockLatch.Release();
                    foreach (JobHandle handle in handles)
                    {
                        handle.Cancel(false);
                    }
                    return;
                }
            } while (System.nanoTime() < deadline);
            fail("Only managed to start " + startedCounter.get() + " tasks in 10 seconds, when " + handles.Count + " was expected.");
        }
Beispiel #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void tryCheckPointMustWaitForOnGoingCheckPointsToCompleteAsLongAsTimeoutPredicateIsFalse() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TryCheckPointMustWaitForOnGoingCheckPointsToCompleteAsLongAsTimeoutPredicateIsFalse()
        {
            MockTxIdStore();
            CheckPointerImpl checkPointer        = checkPointer();
            BinaryLatch      arriveFlushAndForce = new BinaryLatch();
            BinaryLatch      finishFlushAndForce = new BinaryLatch();

            doAnswer(invocation =>
            {
                arriveFlushAndForce.Release();
                finishFlushAndForce.Await();
                return(null);
            }).when(_storageEngine).flushAndForce(_limiter);

            Thread forceCheckPointThread = new Thread(() =>
            {
                try
                {
                    checkPointer.ForceCheckPoint(_info);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                    Console.Write(e.StackTrace);
                    throw new Exception(e);
                }
            });

            forceCheckPointThread.Start();

            arriveFlushAndForce.Await();               // Wait for force-thread to arrive in flushAndForce().

            System.Func <bool> predicate = mock(typeof(System.Func <bool>));
            when(predicate()).thenReturn(false, false, true);
            assertThat(checkPointer.TryCheckPoint(_info, predicate), @is(-1L)); // We decided to not wait for the on-going check point to finish.

            finishFlushAndForce.Release();                                      // Let the flushAndForce complete.
            forceCheckPointThread.Join();

            assertThat(checkPointer.TryCheckPoint(_info, predicate), @is(this._transactionId));
        }
Beispiel #10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 10_000) public void scheduledTasksThatThrowsShouldStop() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ScheduledTasksThatThrowsShouldStop()
        {
            CentralJobScheduler scheduler = new CentralJobScheduler();

            scheduler.Init();

            BinaryLatch   triggerLatch   = new BinaryLatch();
            Exception     boom           = new Exception("boom");
            AtomicInteger triggerCounter = new AtomicInteger();
            ThreadStart   job            = () =>
            {
                triggerCounter.incrementAndGet();
                triggerLatch.Release();
                throw boom;
            };

            scheduler.ScheduleRecurring(Group.INDEX_POPULATION, job, 1, TimeUnit.MILLISECONDS);

            triggerLatch.Await();
            Thread.Sleep(50);

            assertThat(triggerCounter.get(), @is(1));
        }
Beispiel #11
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void registerUnregisterWithConcurrentTransactions() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RegisterUnregisterWithConcurrentTransactions()
        {
            ExecutorService  executor         = Executors.newFixedThreadPool(2);
            AtomicInteger    runningCounter   = new AtomicInteger();
            AtomicInteger    doneCounter      = new AtomicInteger();
            BinaryLatch      startLatch       = new BinaryLatch();
            RelationshipType relationshipType = RelationshipType.withName("REL");

            CountingTransactionEventHandler[] handlers = new CountingTransactionEventHandler[20];
            for (int i = 0; i < handlers.Length; i++)
            {
                handlers[i] = new CountingTransactionEventHandler();
            }
            long relNodeId;

            using (Transaction tx = _db.beginTx())
            {
                relNodeId = _db.createNode().Id;
                tx.Success();
            }
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> nodeCreator = executor.submit(() ->
            Future <object> nodeCreator = executor.submit(() =>
            {
                try
                {
                    runningCounter.incrementAndGet();
                    startLatch.Await();
                    for (int i = 0; i < 2_000; i++)
                    {
                        using (Transaction tx = _db.beginTx())
                        {
                            _db.createNode();
                            if (ThreadLocalRandom.current().nextBoolean())
                            {
                                tx.Success();
                            }
                        }
                    }
                }
                finally
                {
                    doneCounter.incrementAndGet();
                }
            });
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> relationshipCreator = executor.submit(() ->
            Future <object> relationshipCreator = executor.submit(() =>
            {
                try
                {
                    runningCounter.incrementAndGet();
                    startLatch.Await();
                    for (int i = 0; i < 1_000; i++)
                    {
                        using (Transaction tx = _db.beginTx())
                        {
                            Node relNode = _db.getNodeById(relNodeId);
                            relNode.createRelationshipTo(relNode, relationshipType);
                            if (ThreadLocalRandom.current().nextBoolean())
                            {
                                tx.Success();
                            }
                        }
                    }
                }
                finally
                {
                    doneCounter.incrementAndGet();
                }
            });

            while (runningCounter.get() < 2)
            {
                Thread.yield();
            }
            int i = 0;

            _db.registerTransactionEventHandler(handlers[i]);
            CountingTransactionEventHandler currentlyRegistered = handlers[i];

            i++;
            startLatch.Release();
            while (doneCounter.get() < 2)
            {
                _db.registerTransactionEventHandler(handlers[i]);
                i++;
                if (i == handlers.Length)
                {
                    i = 0;
                }
                _db.unregisterTransactionEventHandler(currentlyRegistered);
                currentlyRegistered = handlers[i];
            }
            nodeCreator.get();
            relationshipCreator.get();
            foreach (CountingTransactionEventHandler handler in handlers)
            {
                assertEquals(0, handler.get());
            }
        }