Beispiel #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotifyCancelListeners()
        public virtual void ShouldNotifyCancelListeners()
        {
            // GIVEN
            CentralJobScheduler centralJobScheduler = new CentralJobScheduler();

            centralJobScheduler.Init();

            // WHEN
            AtomicBoolean halted = new AtomicBoolean();
            ThreadStart   job    = () =>
            {
                while (!halted.get())
                {
                    LockSupport.parkNanos(MILLISECONDS.toNanos(10));
                }
            };
            JobHandle handle = centralJobScheduler.Schedule(Group.INDEX_POPULATION, job);

            handle.RegisterCancelListener(mayBeInterrupted => halted.set(true));
            handle.Cancel(false);

            // THEN
            assertTrue(halted.get());
            centralJobScheduler.Shutdown();
        }
        // 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());
        }
Beispiel #3
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotAcceptMoreJobsThanAllowed() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotAcceptMoreJobsThanAllowed()
        {
            // given
            when(_config.jobLimit()).thenReturn(1);
            JobScheduler jobScheduler = createInitialisedScheduler();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker(config, jobScheduler);
            IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker(_config, jobScheduler);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch latch = new org.neo4j.test.DoubleLatch();
            DoubleLatch latch = new DoubleLatch();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch waitingLatch = new org.neo4j.test.DoubleLatch();
            DoubleLatch waitingLatch = new DoubleLatch();

            // when
            assertTrue(jobTracker.CanExecuteMoreSamplingJobs());

            jobTracker.ScheduleSamplingJob(new IndexSamplingJobAnonymousInnerClass2(this, latch));

            // then
            latch.WaitForAllToStart();

            assertFalse(jobTracker.CanExecuteMoreSamplingJobs());

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

            (new Thread(() =>
            {
                waiting.set(true);
                waitingLatch.StartAndWaitForAllToStart();
                jobTracker.WaitUntilCanExecuteMoreSamplingJobs();
                waiting.set(false);
                waitingLatch.Finish();
            })).Start();

            waitingLatch.WaitForAllToStart();

            assertTrue(waiting.get());

            latch.Finish();

            waitingLatch.WaitForAllToFinish();

            assertFalse(waiting.get());

            // eventually we accept new jobs
            while (!jobTracker.CanExecuteMoreSamplingJobs())
            {
                Thread.yield();
            }
        }
Beispiel #4
0
 /// <returns> A stream outputting to the latest output file </returns>
 public override Stream Get()
 {
     if (!_closed.get() && !_rotating.get())
     {
         // In case output file doesn't exist, call rotate so that it gets created
         if (RotationDelayExceeded() && RotationThresholdExceeded() || !_fileSystem.fileExists(_outputFile))
         {
             Rotate();
         }
     }
     return(this._streamWrapper);
 }
Beispiel #5
0
 /**
  * Set to true if this page @is being compiled.
  */
 public void waitForCompile()
 {
     synchronized(this)
     {
         if (_isCompiling.get())
         {
             try {
                 wait(120000);
             } catch (Exception e) {
                 log.log(Level.WARNING, e.ToString(), e);
             }
         }
     }
 }
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 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());
        }
            public override void Run()
            {
                try
                {
                    TransactionQueue queue = new TransactionQueue(BatchSize, (tx, last) =>
                    {
                        // Apply
                        StorageEngine.apply(tx, TransactionApplicationMode.EXTERNAL);

                        // And verify that all nodes are in the index
                        VerifyIndex(tx);
                        Base += BatchSize;
                    });
                    for ( ; !End.get(); I++)
                    {
                        queue.Queue(CreateNodeAndProperty(I));
                    }
                    queue.Empty();
                }
                catch (Exception e)
                {
                    throw new Exception(e);
                }
                finally
                {
                    CommandCreationContext.close();
                }
            }
Beispiel #8
0
        internal String fixForNamespace(String path, bool isSequential)
        {
            if (ensurePathNeeded.get())
            {
                try
                {
                    CuratorZookeeperClient zookeeperClient = client.getZookeeperClient();
                    RetryLoop.callWithRetry
                    (
                        zookeeperClient,
                        CallableUtils.FromFunc <object>(() =>
                    {
                        ZKPaths.mkdirs(zookeeperClient.getZooKeeper(),
                                       ZKPaths.makePath("/", @namespace),
                                       true,
                                       client.getAclProvider(),
                                       true);
                        return(null);
                    })
                    );
                    ensurePathNeeded.set(false);
                }
                catch (Exception e)
                {
                    ThreadUtils.checkInterrupted(e);
                    client.logError("Ensure path threw exception", e);
                }
            }

            return(ZKPaths.fixForNamespace(@namespace, path, isSequential));
        }
Beispiel #9
0
 /**
  * The first time this method is called, all nodes in the
  * path will be created as containers if needed
  *
  * @throws Exception errors
  */
 public void ensure()
 {
     if (ensureNeeded.get())
     {
         internalEnsure();
     }
 }
Beispiel #10
0
 public override void Run()
 {
     Runner = Thread.CurrentThread;
     try
     {
         Pool.acquire();
         OnAcquire.Signal();
         try
         {
             Latch.acquire();
         }
         catch (InterruptedException e)
         {
             throw new Exception(e);
         }
         if (ReleaseConflict.get())
         {
             Pool.release();
             Released.Signal();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         Console.Write(e.StackTrace);
     }
 }
Beispiel #11
0
 public override void Run()
 {
     while (!StopFlag.get())
     {
         try
         {
             using (Transaction transaction = outerInstance.EmbeddedDatabase.beginTx())
             {
                 bool deleteOnBands = ThreadLocalRandom.current().nextBoolean();
                 if (deleteOnBands)
                 {
                     DeleteRelationshipOfRandomType();
                 }
                 else
                 {
                     DeleteRelationshipOnRandomNode();
                 }
                 transaction.Success();
                 RemovalCount++;
             }
         }
         catch (Exception ignored) when(ignored is DeadlockDetectedException || ignored is NotFoundException)
         {
             // ignore deadlocks
         }
         LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(15));
     }
 }
Beispiel #12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 5_000) public void shouldAcceptNewJobWhenRunningJobFinishes() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAcceptNewJobWhenRunningJobFinishes()
        {
            // Given
            when(_config.jobLimit()).thenReturn(1);

            JobScheduler jobScheduler = createInitialisedScheduler();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker(config, jobScheduler);
            IndexSamplingJobTracker jobTracker = new IndexSamplingJobTracker(_config, jobScheduler);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.DoubleLatch latch = new org.neo4j.test.DoubleLatch();
            DoubleLatch latch = new DoubleLatch();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean lastJobExecuted = new java.util.concurrent.atomic.AtomicBoolean();
            AtomicBoolean lastJobExecuted = new AtomicBoolean();

            jobTracker.ScheduleSamplingJob(new IndexSamplingJobAnonymousInnerClass3(this, latch));

            // When
            Executors.newSingleThreadExecutor().execute(() =>
            {
                jobTracker.WaitUntilCanExecuteMoreSamplingJobs();
                jobTracker.ScheduleSamplingJob(new IndexSamplingJobAnonymousInnerClass4(this, latch, lastJobExecuted));
            });

            assertFalse(jobTracker.CanExecuteMoreSamplingJobs());
            latch.StartAndWaitForAllToStart();
            latch.WaitForAllToFinish();

            // Then
            assertTrue(lastJobExecuted.get());
        }
Beispiel #13
0
        private bool Recover(File storeDir, LogFiles logFiles)
        {
            LifeSupport     life    = new LifeSupport();
            RecoveryMonitor monitor = mock(typeof(RecoveryMonitor));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean recoveryRequired = new java.util.concurrent.atomic.AtomicBoolean();
            AtomicBoolean recoveryRequired = new AtomicBoolean();

            try
            {
                StorageEngine storageEngine = mock(typeof(StorageEngine));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.impl.transaction.log.entry.LogEntryReader<org.neo4j.kernel.impl.transaction.log.ReadableClosablePositionAwareChannel> reader = new org.neo4j.kernel.impl.transaction.log.entry.VersionAwareLogEntryReader<>();
                LogEntryReader <ReadableClosablePositionAwareChannel> reader = new VersionAwareLogEntryReader <ReadableClosablePositionAwareChannel>();
                LogTailScanner tailScanner = GetTailScanner(logFiles, reader);

                TransactionMetadataCache metadataCache = new TransactionMetadataCache();
                LogicalTransactionStore  txStore       = new PhysicalLogicalTransactionStore(logFiles, metadataCache, reader, _monitors, false);
                CorruptedLogsTruncator   logPruner     = new CorruptedLogsTruncator(storeDir, logFiles, FileSystemRule.get());
                life.add(new Recovery(new DefaultRecoveryServiceAnonymousInnerClass3(this, storageEngine, tailScanner, _transactionIdStore, txStore, _versionRepository, NO_MONITOR, recoveryRequired)
                                      , logPruner, _schemaLife, monitor, SilentProgressReporter.INSTANCE, false));

                life.Start();
            }
            finally
            {
                life.Shutdown();
            }
            return(recoveryRequired.get());
        }
Beispiel #14
0
 private static void RepeatedlyPopulateDatabase <T1>(Cluster <T1> cluster, AtomicBoolean continueFlagReference)
 {
     while (continueFlagReference.get())
     {
         CreateSomeData(cluster);
     }
 }
Beispiel #15
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldExecuteAllFailingOperations()
        public virtual void ShouldExecuteAllFailingOperations()
        {
            AtomicBoolean @bool = new AtomicBoolean(false);

            try
            {
                ErrorHandler.RunAll("test", Assert.fail, () =>
                {
                    @bool.set(true);
                    throw new System.InvalidOperationException(FAILMESSAGE);
                });
                fail();
            }
            catch (Exception e)
            {
                assertEquals("test", e.Message);
                Exception cause = e.InnerException;
                assertEquals(typeof(AssertionError), cause.GetType());
                Exception[] suppressed = e.Suppressed;
                assertEquals(1, suppressed.Length);
                assertEquals(typeof(System.InvalidOperationException), suppressed[0].GetType());
                assertEquals("More fail", suppressed[0].Message);
                assertTrue(@bool.get());
            }
        }
Beispiel #16
0
        /// <summary>
        /// This test makes sure that the database is able to start after having been stopped during initialization.
        ///
        /// In order to make sure that the server is stopped during startup we create a separate thread that calls stop.
        /// In order to make sure that this thread does not call stop before the startup procedure has started we use a
        /// custom implementation of a PageSwapperFactory, which communicates with the thread that calls stop. We do this
        /// via a static semaphore. </summary>
        /// <exception cref="IOException"> </exception>
        /// <exception cref="InterruptedException"> </exception>

//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBeAbleToRestartWhenStoppedDuringStartup() throws java.io.IOException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBeAbleToRestartWhenStoppedDuringStartup()
        {
            // Make sure that the semaphore is in a clean state.
            _semaphore.drainPermits();
            // Get a server that uses our custom swapper.
            NeoServer server = GetNeoServer(CUSTOM_SWAPPER);

            try
            {
                AtomicBoolean failure = new AtomicBoolean();
                Thread        serverStoppingThread = ThreadTestUtils.fork(StopServerAfterStartingHasStarted(server, failure));
                server.Start();
                // Wait for the server to stop.
                serverStoppingThread.Join();
                // Check if the server stopped successfully.
                if (failure.get())
                {
                    fail("Server failed to stop.");
                }
                // Verify that we can start the server again.
                server = GetNeoServer(CUSTOM_SWAPPER);
                server.Start();
            }
            finally
            {
                server.Stop();
            }
        }
 public override void Run()
 {
     while (ShouldContinue.get())
     {
         Stress();
     }
 }
Beispiel #18
0
        public override object deref()
        {
            registerDep(this);

            if (!dirty.get())
            {
                return(state.Get());
            }

            try
            {
                Var.pushThreadBindings(RT.map(REGISTER_DEP, registerDepInst));
                for (;;)
                {
                    dirty.set(false);
                    var v    = state.Get();
                    var newv = compute();
                    Validate(newv);
                    if (state.CompareAndSet(v, newv))
                    {
                        NotifyWatches(v, newv);
                        return(newv);
                    }
                }
            }
            finally
            {
                Var.popThreadBindings();
            }
        }
Beispiel #19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void writeOneIteration(TestCoordinator testCoordinator, java.util.concurrent.atomic.AtomicBoolean failHalt) throws java.io.IOException, InterruptedException
        private void WriteOneIteration(TestCoordinator testCoordinator, AtomicBoolean failHalt)
        {
            int batchSize = testCoordinator.WriteBatchSize();
            IEnumerable <UpdateOperation> toWrite         = testCoordinator.NextToWrite();
            IEnumerator <UpdateOperation> toWriteIterator = toWrite.GetEnumerator();

            while (toWriteIterator.MoveNext())
            {
                using (Writer <KEY, VALUE> writer = _index.writer())
                {
                    int inBatch = 0;
                    while (toWriteIterator.MoveNext() && inBatch < batchSize)
                    {
                        UpdateOperation operation = toWriteIterator.Current;
                        operation.Apply(writer);
                        if (failHalt.get())
                        {
                            break;
                        }
                        inBatch++;
                    }
                }
                // Sleep to allow checkpointer to step in
                MILLISECONDS.sleep(1);
            }
        }
Beispiel #20
0
            public override void Run()
            {
                try
                {
                    ReadySignal.Signal();
                    awaitLatch(StartSignal);
                    while (!End.get())
                    {
                        long id;

                        // Ids must be offered in order
                        lock ( Queue )
                        {
                            id = IdSource.next();
                            Queue.offer(id);
                        }

                        Queue.waitFor(id);
                        for (int i = 0, max = Random.Next(10_000); i < max; i++)
                        {
                            // Jit - please don't take this loop away. Look busy... check queue for empty, or something!
                            Queue.Empty;
                        }
                        Queue.removeChecked(id);
                    }
                }
                catch (Exception e)
                {
                    this.Exception = e;
                }
            }
Beispiel #21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBlockUntilTheIndexIsOnline() throws org.neo4j.internal.kernel.api.exceptions.schema.IndexNotFoundKernelException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBlockUntilTheIndexIsOnline()
        {
            when(_tokenRead.nodeLabel(anyString())).thenReturn(0);
            when(_tokenRead.propertyKey(anyString())).thenReturn(0);
            when(_schemaRead.index(anyInt(), any())).thenReturn(_anyIndex);

            AtomicReference <InternalIndexState> state = new AtomicReference <InternalIndexState>(POPULATING);

            when(_schemaRead.indexGetState(any(typeof(IndexReference)))).then(invocationOnMock => state.get());

            AtomicBoolean done = new AtomicBoolean(false);

            (new Thread(() =>
            {
                try
                {
                    _procedure.awaitIndexByPattern(":Person(name)", TIMEOUT, _timeUnit);
                }
                catch (ProcedureException e)
                {
                    throw new Exception(e);
                }
                done.set(true);
            })).Start();

            assertThat(done.get(), @is(false));

            state.set(ONLINE);
            assertEventually("Procedure did not return after index was online", done.get, @is(true), TIMEOUT, _timeUnit);
        }
Beispiel #22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldAcceptTransactionCommittedWithNoLockManager() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldAcceptTransactionCommittedWithNoLockManager()
        {
            // given
            int  txLockSessionId      = Org.Neo4j.Kernel.impl.locking.Locks_Client_Fields.NO_LOCK_SESSION_ID;
            int  currentLockSessionId = 24;
            long txId = 42L;

            ReplicatedTransaction tx = ReplicatedTransaction.from(PhysicalTx(txLockSessionId));

            TransactionCommitProcess localCommitProcess = CreateFakeTransactionCommitProcess(txId);

            ReplicatedTransactionStateMachine stateMachine = new ReplicatedTransactionStateMachine(_commandIndexTracker, LockState(currentLockSessionId), _batchSize, _logProvider, Org.Neo4j.Io.pagecache.tracing.cursor.PageCursorTracerSupplier_Fields.Null, EmptyVersionContextSupplier.EMPTY);

            stateMachine.InstallCommitProcess(localCommitProcess, -1L);

            AtomicBoolean called = new AtomicBoolean();

            // when
            stateMachine.ApplyCommand(tx, 0, result =>
            {
                // then
                called.set(true);
                try
                {
                    assertEquals(txId, ( long )result.consume());
                }
                catch (Exception e)
                {
                    throw new Exception(e);
                }
            });
            stateMachine.EnsuredApplied();

            assertTrue(called.get());
        }
Beispiel #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void mustNotApplyAsyncWorkInParallelUnderStress() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void MustNotApplyAsyncWorkInParallelUnderStress()
        {
            int workers        = Runtime.Runtime.availableProcessors() * 5;
            int iterations     = 1_000;
            int incrementValue = 42;

            System.Threading.CountdownEvent startLatch = new System.Threading.CountdownEvent(workers);
            System.Threading.CountdownEvent endLatch   = new System.Threading.CountdownEvent(workers);
            AtomicBoolean   start = new AtomicBoolean();
            Callable <Void> work  = () =>
            {
                startLatch.Signal();
                bool spin;
                do
                {
                    spin = !start.get();
                } while (spin);

                ThreadLocalRandom  rng    = ThreadLocalRandom.current();
                IList <AsyncApply> asyncs = new List <AsyncApply>();
                for (int i = 0; i < iterations; i++)
                {
                    asyncs.add(_sync.applyAsync(new AddWork(incrementValue)));
                    if (rng.Next(10) == 0)
                    {
                        foreach (AsyncApply async in asyncs)
                        {
                            async.Await();
                        }
                        asyncs.clear();
                    }
                }

                foreach (AsyncApply async in asyncs)
                {
                    async.Await();
                }
                endLatch.Signal();
                return(null);
            };

            IList <Future <Void> > futureList = new List <Future <Void> >();

            for (int i = 0; i < workers; i++)
            {
                futureList.Add(_executor.submit(work));
            }
            startLatch.await();
            start.set(true);
            endLatch.await();

            foreach (Future <Void> future in futureList)
            {
                future.get();                         // check for any exceptions
            }

            assertThat(_count.sum(), lessThan((long)(workers * iterations)));
            assertThat(_sum.sum(), @is((long)(incrementValue * workers * iterations)));
        }
Beispiel #24
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldOpenAndRecoverExistingData() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldOpenAndRecoverExistingData()
        {
            // GIVEN
            TransactionIdStore       transactionIdStore = new SimpleTransactionIdStore();
            TransactionMetadataCache positionCache      = new TransactionMetadataCache();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final byte[] additionalHeader = new byte[]{1, 2, 5};
            sbyte[]     additionalHeader             = new sbyte[] { 1, 2, 5 };
            const int   masterId                     = 2;
            int         authorId                     = 1;
            const long  timeStarted                  = 12345;
            long        latestCommittedTxWhenStarted = 4545;
            long        timeCommitted                = timeStarted + 10;
            LifeSupport life = new LifeSupport();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.impl.transaction.log.files.LogFiles logFiles = org.neo4j.kernel.impl.transaction.log.files.LogFilesBuilder.builder(dir.databaseLayout(), fileSystemRule.get()).withTransactionIdStore(transactionIdStore).withLogVersionRepository(mock(LogVersionRepository.class)).build();
            LogFiles logFiles = LogFilesBuilder.builder(Dir.databaseLayout(), FileSystemRule.get()).withTransactionIdStore(transactionIdStore).withLogVersionRepository(mock(typeof(LogVersionRepository))).build();

            life.Start();
            life.Add(logFiles);
            try
            {
                AddATransactionAndRewind(life, logFiles, positionCache, transactionIdStore, additionalHeader, masterId, authorId, timeStarted, latestCommittedTxWhenStarted, timeCommitted);
            }
            finally
            {
                life.Shutdown();
            }

            life = new LifeSupport();
            life.Add(logFiles);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean recoveryRequired = new java.util.concurrent.atomic.AtomicBoolean();
            AtomicBoolean       recoveryRequired = new AtomicBoolean();
            FakeRecoveryVisitor visitor          = new FakeRecoveryVisitor(additionalHeader, masterId, authorId, timeStarted, timeCommitted, latestCommittedTxWhenStarted);

            LogicalTransactionStore txStore = new PhysicalLogicalTransactionStore(logFiles, positionCache, new VersionAwareLogEntryReader <ReadableClosablePositionAwareChannel>(), _monitors, true);

            life.Add(new BatchingTransactionAppender(logFiles, NO_ROTATION, positionCache, transactionIdStore, BYPASS, _databaseHealth));
            CorruptedLogsTruncator logPruner = new CorruptedLogsTruncator(_databaseDirectory, logFiles, FileSystemRule.get());

            life.add(new Recovery(new RecoveryServiceAnonymousInnerClass(this, recoveryRequired, visitor, txStore)
                                  , logPruner, new LifecycleAdapter(), mock(typeof(RecoveryMonitor)), SilentProgressReporter.INSTANCE, false));

            // WHEN
            try
            {
                life.Start();
            }
            finally
            {
                life.Shutdown();
            }

            // THEN
            assertEquals(1, visitor.VisitedTransactions);
            assertTrue(recoveryRequired.get());
        }
Beispiel #25
0
 public override void add(int delta)
 {
     if (_broken.get())
     {
         throw new System.InvalidOperationException("boom!");
     }
     base.add(delta);
 }
 private Answer <T> NewBlockingAnswer <T>(AtomicInteger counter, AtomicBoolean exitCondition)
 {
     return(invocationOnMock =>
     {
         counter.incrementAndGet();
         Predicates.awaitForever(() => Thread.CurrentThread.Interrupted || exitCondition.get(), 500, MILLISECONDS);
         return null;
     });
 }
Beispiel #27
0
 internal virtual void AddBytes(long n)
 {
     _currentBytes += n;
     if (_printUpdate.get())
     {
         PrintProgress();
         _printUpdate.set(false);
     }
 }
 public double yearFraction(LocalDate firstDate, LocalDate secondDate, com.opengamma.strata.basics.date.DayCount_ScheduleInfo scheduleInfo)
 {
     assertEquals(scheduleInfo.StartDate, @base.UnadjustedStartDate);
     assertEquals(scheduleInfo.EndDate, @base.UnadjustedEndDate);
     assertEquals(scheduleInfo.getPeriodEndDate(firstDate), period.UnadjustedEndDate);
     assertEquals(scheduleInfo.Frequency, @base.Frequency);
     assertEquals(scheduleInfo.EndOfMonthConvention, eom.get());
     return(0.5);
 }
Beispiel #29
0
        public Control(Config config)
        {
            this._log = config.LogProvider().getLog(this.GetType());
            long workDurationMinutes = config.WorkDurationMinutes();

            this._totalDurationMinutes = workDurationMinutes + config.ShutdownDurationMinutes();

            System.Func <bool> notExpired = untilTimeExpired(workDurationMinutes, MINUTES);
            this._keepGoing = () => !_stopTheWorld.get() && notExpired();
        }
Beispiel #30
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void mustFlushAsFastAsPossibleDuringTryCheckPoint() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void MustFlushAsFastAsPossibleDuringTryCheckPoint()
        {
            AtomicBoolean doneDisablingLimits = new AtomicBoolean();

            _limiter = new IOLimiterAnonymousInnerClass3(this, doneDisablingLimits);
            MockTxIdStore();
            CheckPointerImpl checkPointer = checkPointer();

            checkPointer.TryCheckPoint(_info);
            assertTrue(doneDisablingLimits.get());
        }