Esempio n. 1
0
        public virtual void AwaitUpdateApplication()
        {
            BinaryLatch updateLatch = new BinaryLatch();

            _scheduler.schedule(Group.INDEX_UPDATING, updateLatch.release);
            updateLatch.Await();
        }
Esempio n. 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));
        }
Esempio n. 3
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static void runTest(Fixture fixture) throws InterruptedException, java.util.concurrent.ExecutionException
        private static void RunTest(Fixture fixture)
        {
            int          iterations   = fixture.Iterations();
            ResourceType resourceType = fixture.CreateResourceType();
            Locks        manager      = fixture.CreateLockManager(resourceType);

            try
            {
                using (Org.Neo4j.Kernel.impl.locking.Locks_Client a = manager.NewClient(), Org.Neo4j.Kernel.impl.locking.Locks_Client b = manager.NewClient())
                {
                    BinaryLatch     startLatch = new BinaryLatch();
                    BlockedCallable callA      = new BlockedCallable(startLatch, () => workloadA(fixture, a, resourceType, iterations));
                    BlockedCallable callB      = new BlockedCallable(startLatch, () => workloadB(fixture, b, resourceType, iterations));

                    Future <Void> futureA = _executor.submit(callA);
                    Future <Void> futureB = _executor.submit(callB);

                    callA.AwaitBlocked();
                    callB.AwaitBlocked();

                    startLatch.Release();

                    futureA.get();
                    futureB.get();
                }
            }
            finally
            {
                manager.Close();
            }
        }
Esempio n. 4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void takeOrAwaitLatchMustReturnLatchIfAvailable()
        internal virtual void TakeOrAwaitLatchMustReturnLatchIfAvailable()
        {
            BinaryLatch latch = _latches.takeOrAwaitLatch(0);

            assertThat(latch, @is(notNullValue()));
            latch.Release();
        }
Esempio n. 5
0
 internal ScheduledJobHandle(TimeBasedTaskScheduler scheduler, Group group, ThreadStart task, long nextDeadlineNanos, long reschedulingDelayNanos)
 {
     this._group            = group;
     this.NextDeadlineNanos = nextDeadlineNanos;
     _handleRelease         = new BinaryLatch();
     _cancelListeners       = new CopyOnWriteArrayList <CancelListener>();
     this._task             = () =>
     {
         try
         {
             task.run();
             // Use compareAndSet to avoid overriding any cancellation state.
             if (compareAndSet(SUBMITTED, RUNNABLE) && reschedulingDelayNanos > 0)
             {
                 // We only reschedule if the rescheduling delay is greater than zero.
                 // A rescheduling delay of zero means this is a delayed task.
                 // If the rescheduling delay is greater than zero, then this is a recurring task.
                 this.NextDeadlineNanos += reschedulingDelayNanos;
                 scheduler.EnqueueTask(this);
             }
         }
         catch (Exception e)
         {
             _lastException = e;
             set(FAILED);
         }
     };
 }
Esempio n. 6
0
        public virtual bool TryLock(int recordId)
        {
            int?        record        = recordId;
            BinaryLatch myLatch       = new BinaryLatch();
            BinaryLatch existingLatch = _map.GetOrAdd(record, myLatch);

            return(existingLatch == null);
        }
Esempio n. 7
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();
        }
Esempio n. 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void takeOrAwaitLatchMustNotLetUnrelatedLatchesConflictTooMuch() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void TakeOrAwaitLatchMustNotLetUnrelatedLatchesConflictTooMuch()
        {
            BinaryLatch latch = _latches.takeOrAwaitLatch(42);

            assertThat(latch, @is(notNullValue()));
            ExecutorService      executor = Executors.newSingleThreadExecutor();
            Future <BinaryLatch> future   = executor.submit(() => _latches.takeOrAwaitLatch(33));

            assertThat(future.get(1, TimeUnit.SECONDS), @is(notNullValue()));
            latch.Release();
        }
Esempio n. 9
0
        public override void Start()
        {
            if (_shutdownLatch != null)
            {
                return;                         // This SlaveUpdatePuller has already been initialised
            }

            _shutdownLatch = new BinaryLatch();
            JobHandle handle = _jobScheduler.schedule(Group.PULL_UPDATES, this);

            handle.RegisterCancelListener(this);
        }
Esempio n. 10
0
        public override void Stop()          // for removing throw declaration
        {
            if (_shutdownLatch == null)
            {
                return;                         // This SlaveUpdatePuller has already been shut down
            }

            Thread thread = _updatePullingThread;

            _halted = true;
            LockSupport.unpark(thread);
            _shutdownLatch.await();
            _shutdownLatch = null;
        }
Esempio n. 11
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());
        }
Esempio n. 12
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 shutDownMustKillCancelledJobs()
        public virtual void ShutDownMustKillCancelledJobs()
        {
            CentralJobScheduler scheduler = new CentralJobScheduler();

            scheduler.Init();

            BinaryLatch startLatch = new BinaryLatch();
            BinaryLatch stopLatch  = new BinaryLatch();

            scheduler.Schedule(Group.INDEX_POPULATION, () =>
            {
                try
                {
                    startLatch.Release();
                    Thread.Sleep(100_000);
                }
Esempio n. 13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void longRunningTasksMustNotDelayExecutionOfOtherTasks() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void LongRunningTasksMustNotDelayExecutionOfOtherTasks()
        {
            BinaryLatch latch        = new BinaryLatch();
            ThreadStart longRunning  = latch.await;
            ThreadStart shortRunning = _semaphore.release;

            _scheduler.submit(Group.STORAGE_MAINTENANCE, longRunning, 100, 100);
            _scheduler.submit(Group.STORAGE_MAINTENANCE, shortRunning, 100, 100);
            for (int i = 0; i < 4; i++)
            {
                _clock.forward(100, TimeUnit.NANOSECONDS);
                _scheduler.tick();
                AssertSemaphoreAcquire();
            }
            latch.Release();
        }
Esempio n. 14
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()));
        }
Esempio n. 15
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()));
        }
Esempio n. 16
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();
                }
            }
        }
Esempio n. 17
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.");
        }
Esempio n. 18
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));
        }
Esempio n. 19
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void takeOrAwaitLatchMustAwaitExistingLatchAndReturnNull() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void TakeOrAwaitLatchMustAwaitExistingLatchAndReturnNull()
        {
            AtomicReference <Thread> threadRef = new AtomicReference <Thread>();
            BinaryLatch latch = _latches.takeOrAwaitLatch(42);

            assertThat(latch, @is(notNullValue()));
            ExecutorService      executor = Executors.newSingleThreadExecutor();
            Future <BinaryLatch> future   = executor.submit(() =>
            {
                threadRef.set(Thread.CurrentThread);
                return(_latches.takeOrAwaitLatch(42));
            });
            Thread th;

            do
            {
                th = threadRef.get();
            } while (th == null);
            ThreadTestUtils.awaitThreadState(th, 10_000, Thread.State.WAITING);
            latch.Release();
            assertThat(future.get(1, TimeUnit.SECONDS), @is(nullValue()));
        }
Esempio n. 20
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));
        }
Esempio n. 21
0
 public IOLimiterAnonymousInnerClass4(CheckPointerImplTest outerInstance, AtomicLong limitDisableCounter, BinaryLatch forceCheckPointStartLatch)
 {
     this.outerInstance              = outerInstance;
     this._limitDisableCounter       = limitDisableCounter;
     this._forceCheckPointStartLatch = forceCheckPointStartLatch;
 }
Esempio n. 22
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());
            }
        }
Esempio n. 23
0
 internal BlockedCallable(BinaryLatch startLatch, ThrowingAction <Exception> @delegate)
 {
     this.StartLatch = startLatch;
     this.Delegate   = @delegate;
 }