Beispiel #1
0
        protected internal virtual void suspendAcquisition(long millis)
        {
            if (millis <= 0)
            {
                return;
            }

            try
            {
                LOG.debugJobAcquisitionThreadSleeping(millis);
                lock (MONITOR)
                {
                    if (!isInterrupted)
                    {
                        isWaiting.set(true);
                        Monitor.Wait(MONITOR, TimeSpan.FromMilliseconds(millis));
                    }
                }
                LOG.jobExecutorThreadWokeUp();
            }
            catch (InterruptedException)
            {
                LOG.jobExecutionWaitInterrupted();
            }
            finally
            {
                isWaiting.set(false);
            }
        }
Beispiel #2
0
 private void ThreadProc()
 {
     try
     {
         model.GetNumUsers();
         initialized.set(true);
     } catch (TasteException te) {
         // oops
     }
 }
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
 protected internal override EntryUpdater <Key> Updater(long version, Lock @lock)
 {
     Update(HighestAppliedVersion, version);
     if (version > Threshold)
     {
         HasTrackedChanges.set(true);
         return(new Updater <Key>(@lock, Store, Changes, AppliedChanges, version));
     }
     else
     {
         return(new Updater <Key>(@lock, Store, Changes, null, version));
     }
 }
Beispiel #5
0
 public override void NotifyCommitted(long commitIndex)
 {
     if (commitIndex >= 0)
     {
         Bootstrapped.set(true);
     }
 }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createdWorkerThreadsShouldContainConnectorNameAndRemoteAddressInTheirNamesWhenActive() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void CreatedWorkerThreadsShouldContainConnectorNameAndRemoteAddressInTheirNamesWhenActive()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<String> capturedThreadName = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <string> capturedThreadName = new AtomicReference <string>();

            AtomicInteger  processNextBatchCount = new AtomicInteger();
            string         id            = System.Guid.randomUUID().ToString();
            BoltConnection connection    = NewConnection(id);
            AtomicBoolean  exitCondition = new AtomicBoolean();

            when(connection.ProcessNextBatch()).thenAnswer(inv =>
            {
                capturedThreadName.set(Thread.CurrentThread.Name);
                processNextBatchCount.incrementAndGet();
                return(AwaitExit(exitCondition));
            });

            _boltScheduler.start();
            _boltScheduler.created(connection);
            _boltScheduler.enqueued(connection, Jobs.noop());

            Predicates.await(() => processNextBatchCount.get() > 0, 1, MINUTES);

            assertThat(capturedThreadName.get(), containsString(string.Format("[{0}]", CONNECTOR_KEY)));
            assertThat(capturedThreadName.get(), containsString(string.Format("[{0}]", connection.RemoteAddress())));

            exitCondition.set(true);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void destroyedShouldCancelActiveWorkItem() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DestroyedShouldCancelActiveWorkItem()
        {
            AtomicInteger  processNextBatchCount = new AtomicInteger();
            string         id            = System.Guid.randomUUID().ToString();
            BoltConnection connection    = NewConnection(id);
            AtomicBoolean  exitCondition = new AtomicBoolean();

            when(connection.ProcessNextBatch()).thenAnswer(inv =>
            {
                processNextBatchCount.incrementAndGet();
                return(AwaitExit(exitCondition));
            });

            _boltScheduler.start();
            _boltScheduler.created(connection);
            _boltScheduler.enqueued(connection, Jobs.noop());

            Predicates.await(() => processNextBatchCount.get() > 0, 1, MINUTES);

            _boltScheduler.closed(connection);

            Predicates.await(() => !_boltScheduler.isActive(connection), 1, MINUTES);

            assertFalse(_boltScheduler.isActive(connection));
            assertEquals(1, processNextBatchCount.get());

            exitCondition.set(true);
        }
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
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldClearPreviousChunks()
        public virtual void ShouldClearPreviousChunks()
        {
            // GIVEN
            System.Action <long[]> consumer = mock(typeof(System.Action));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean safeThreshold = new java.util.concurrent.atomic.AtomicBoolean(false);
            AtomicBoolean        safeThreshold = new AtomicBoolean(false);
            DelayedBuffer <long> buffer        = new DelayedBuffer <long>(singleton(0L), t => safeThreshold.get(), 10, consumer);

            // three chunks
            buffer.Offer(0);
            buffer.Maintenance();
            buffer.Offer(1);
            buffer.Maintenance();
            buffer.Offer(2);
            buffer.Maintenance();

            // WHEN
            safeThreshold.set(true);
            buffer.Clear();
            buffer.Maintenance();

            // THEN
            verifyNoMoreInteractions(consumer);
        }
Beispiel #10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void mustRecoverFromExceptions() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void MustRecoverFromExceptions()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean broken = new java.util.concurrent.atomic.AtomicBoolean(true);
            AtomicBoolean broken = new AtomicBoolean(true);
            Adder         adder  = new AdderAnonymousInnerClass(this, broken);

            _sync = new WorkSync <Adder, AddWork>(adder);

            try
            {
                // Run this in a different thread to account for reentrant locks.
                _executor.submit(new CallableWork(this, new AddWork(10))).get();
                fail("Should have thrown");
            }
            catch (ExecutionException exception)
            {
                // Outermost ExecutionException from the ExecutorService
                assertThat(exception.InnerException, instanceOf(typeof(ExecutionException)));

                // Inner ExecutionException from the WorkSync
                exception = ( ExecutionException )exception.InnerException;
                assertThat(exception.InnerException, instanceOf(typeof(System.InvalidOperationException)));
            }

            broken.set(false);
            _sync.apply(new AddWork(20));

            assertThat(_sum.sum(), @is(20L));
            assertThat(_count.sum(), @is(1L));
        }
        /// <seealso cref= CustomSerializer#serializeContent(RequestCommand, InvokeContext) </seealso>
        public override bool serializeContent(RequestCommand req, InvokeContext invokeContext)
        {
            serialFlag.set(true);
            RpcRequestCommand rpcReq = (RpcRequestCommand)req;
            RequestBody       bd     = (RequestBody)rpcReq.RequestObject;
            int id = bd.Id;

            byte[] msg;
            try
            {
                msg = Encoding.UTF8.GetBytes(bd.Msg);
                IByteBuffer bb = UnpooledByteBufferAllocator.Default.Buffer(4 + msg.Length);
                bb.WriteInt(id);
                bb.WriteBytes(msg);
                rpcReq.Content = bb.Array;
            }
            catch (UnsupportedEncodingException e)
            {
                System.Console.WriteLine(e.ToString());
                System.Console.Write(e.StackTrace);
            }

            contentSerializer = rpcReq.Serializer;
            return(true);
        }
        public virtual void ShouldBeAbleToReadPropertiesFromNewNodeReturnedFromIndex()
        {
            string        propertyKey   = System.Guid.randomUUID().ToString();
            string        propertyValue = System.Guid.randomUUID().ToString();
            AtomicBoolean start         = new AtomicBoolean(false);
            int           readerDelay   = ThreadLocalRandom.current().Next(MAX_READER_DELAY_MS);

            Writer writer = new Writer(Db, propertyKey, propertyValue, start);
            Reader reader = new Reader(Db, propertyKey, propertyValue, start, readerDelay);

            ExecutorService executor = Executors.newFixedThreadPool(2);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> readResult;
            Future <object> readResult;
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> writeResult;
            Future <object> writeResult;

            try
            {
                writeResult = executor.submit(writer);
                readResult  = executor.submit(reader);

                start.set(true);
            }
            finally
            {
                executor.shutdown();
                executor.awaitTermination(20, TimeUnit.SECONDS);
            }

            assertNull(writeResult.get());
            assertNull(readResult.get());
        }
Beispiel #13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldNoticeCancelRequest() throws java.io.IOException, java.util.concurrent.ExecutionException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void ShouldNoticeCancelRequest()
        {
            // given
            Org.Neo4j.Test.Barrier_Control barrier = new Org.Neo4j.Test.Barrier_Control();
            TrackingMonitor monitor     = new TrackingMonitorAnonymousInnerClass(this, barrier);
            int             blocks      = 10;
            int             mergeFactor = 2;
            MutableLongSet  uniqueKeys  = new LongHashSet();
            AtomicBoolean   cancelled   = new AtomicBoolean();

            using (BlockStorage <MutableLong, MutableLong> storage = new BlockStorage <MutableLong, MutableLong>(_layout, heapBufferFactory(100), _fileSystem, _file, monitor), OtherThreadExecutor <Void> t2 = new OtherThreadExecutor <Void>("T2", null))
            {
                while (monitor.BlockFlushedCallCount < blocks)
                {
                    storage.Add(UniqueKey(uniqueKeys), new MutableLong());
                }
                storage.DoneAdding();

                // when starting to merge
                Future <object> merge = t2.ExecuteDontWait(command(() => storage.merge(mergeFactor, cancelled.get)));
                barrier.AwaitUninterruptibly();
                // one merge iteration have now been done, set the cancellation flag
                cancelled.set(true);
                barrier.Release();
                merge.get();
            }

            // then there should not be any more merge iterations done, i.e. merge was cancelled
            assertEquals(1, monitor.MergeIterationCallCount);
        }
Beispiel #14
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());
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotScheduleNewJobIfHandlingSchedulingError() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldNotScheduleNewJobIfHandlingSchedulingError()
        {
            AtomicInteger  handleSchedulingErrorCounter = new AtomicInteger(0);
            AtomicBoolean  exitCondition = new AtomicBoolean();
            BoltConnection newConnection = newConnection(System.Guid.randomUUID().ToString());

            doAnswer(NewBlockingAnswer(handleSchedulingErrorCounter, exitCondition)).when(newConnection).handleSchedulingError(any());

            BlockAllThreads();

            // register connection
            _boltScheduler.created(newConnection);

            // send a job and wait for it to enter handleSchedulingError and block there
            CompletableFuture.runAsync(() => _boltScheduler.enqueued(newConnection, Jobs.noop()));
            Predicates.awaitForever(() => handleSchedulingErrorCounter.get() > 0, 500, MILLISECONDS);

            // allow all threads to complete
            _afterExecuteEvent.Signal();
            _afterExecuteBarrier.await();

            // post a job
            _boltScheduler.enqueued(newConnection, Jobs.noop());

            // exit handleSchedulingError
            exitCondition.set(true);

            // verify that handleSchedulingError is called once and processNextBatch never.
            assertEquals(1, handleSchedulingErrorCounter.get());
            verify(newConnection, never()).processNextBatch();
        }
Beispiel #16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void dataIsInAUsableStateAfterBackup() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void DataIsInAUsableStateAfterBackup()
        {
            // given database exists
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: org.neo4j.causalclustering.discovery.Cluster<?> cluster = startCluster(recordFormat);
            Cluster <object> cluster = StartCluster(RecordFormat);

            // and the database has indexes
            ClusterHelper.createIndexes(cluster.GetMemberWithAnyRole(Role.LEADER).database());

            // and the database is being populated
            AtomicBoolean populateDatabaseFlag = new AtomicBoolean(true);
            Thread        thread = new Thread(() => repeatedlyPopulateDatabase(cluster, populateDatabaseFlag));

            thread.Start();               // populate db with number properties etc.
            try
            {
                // then backup is successful
                string address = cluster.AwaitLeader().config().get(online_backup_server).ToString();
                assertEquals(0, RunBackupOtherJvm(address, DATABASE_NAME));
            }
            finally
            {
                populateDatabaseFlag.set(false);
                thread.Join();
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("Duplicates") @Test public void stressCache() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void StressCache()
        {
            StringFactory factory             = new StringFactory();
            TemporalIndexCache <string> cache = new TemporalIndexCache <string>(factory);

            ExecutorService pool = Executors.newFixedThreadPool(20);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?>[] futures = new java.util.concurrent.Future[100];
            Future <object>[] futures        = new Future[100];
            AtomicBoolean     shouldContinue = new AtomicBoolean(true);

            try
            {
                for (int i = 0; i < futures.Length; i++)
                {
                    futures[i] = pool.submit(new CacheStresser(cache, shouldContinue));
                }

                Thread.Sleep(5_000);

                shouldContinue.set(false);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.concurrent.Future<?> future : futures)
                foreach (Future <object> future in futures)
                {
                    future.get(10, TimeUnit.SECONDS);
                }
            }
            finally
            {
                pool.shutdown();
            }
        }
Beispiel #18
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();
        }
Beispiel #19
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 #20
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);
        }
        /// <seealso cref= CustomSerializer#deserializeContent(RequestCommand) </seealso>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public <T extends com.alipay.remoting.rpc.RequestCommand> boolean deserializeContent(T req) throws com.alipay.remoting.exception.DeserializationException
        public override bool deserializeContent(RequestCommand req)
        {
            deserialFlag.set(true);
            RpcRequestCommand rpcReq = (RpcRequestCommand)req;

            byte[]      content = rpcReq.Content;
            IByteBuffer bb      = Unpooled.WrappedBuffer(content);
            int         a       = bb.ReadInt();

            byte[] dst = new byte[content.Length - 4];
            bb.ReadBytes(dst, 0, dst.Length);
            try
            {
                string      b  = Encoding.UTF8.GetString(dst);
                RequestBody bd = new RequestBody(a, b);
                rpcReq.RequestObject = bd;
            }
            catch (UnsupportedEncodingException e)
            {
                System.Console.WriteLine(e.ToString());
                System.Console.Write(e.StackTrace);
            }

            contentDeserializer = rpcReq.Serializer;
            return(true);
        }
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)));
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) throws org.xml.sax.SAXException
            public virtual void startElement(string uri, string localName, string qName, Attributes attributes)
            {
                if (localName.Equals("rendertheme"))
                {
                    isMapsforgeTheme.set(uri.Equals("http://mapsforge.org/renderTheme"));
                    // We have all info, break parsing
                    throw new SAXTerminationException();
                }
            }
        // 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 #26
0
        /**
         * Notifies waiting listeners that compilation has finished.
         */
        public void finishCompiling()
        {
            synchronized(this)
            {
                _isCompiling.set(false);

                notifyAll();
            }
        }
        public void Dispose()
        {
            log.Debug("Connection Closing");

            CloseableUtils.closeQuietly(ensembleProvider);
            try
            {
                zooKeeper.closeAndClear();
            }
            catch (Exception e)
            {
                ThreadUtils.checkInterrupted(e);
                throw new IOException("", e);
            }
            finally
            {
                _isConnected.set(false);
            }
        }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private Runnable endAfterMax(final int time, final java.util.concurrent.TimeUnit unit, final java.util.concurrent.atomic.AtomicBoolean end)
        private ThreadStart EndAfterMax(int time, TimeUnit unit, AtomicBoolean end)
        {
            return(() =>
            {
                long endTime = currentTimeMillis() + unit.toMillis(time);
                while (currentTimeMillis() < endTime && !end.get())
                {
                    parkNanos(MILLISECONDS.toNanos(50));
                }
                end.set(true);
            });
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeOut = 5000) public void interruptHangingResultsListener() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void interruptHangingResultsListener()
        {
            HangingFunction     fn   = new HangingFunction();
            CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL);
            CalculationTask     task = CalculationTask.of(TARGET, fn, cell);
            Column           column  = Column.of(TestingMeasures.PRESENT_VALUE);
            CalculationTasks tasks   = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column));

            ExecutorService executor = Executors.newSingleThreadExecutor();

            try
            {
                CalculationTaskRunner test       = CalculationTaskRunner.of(executor);
                MarketData            marketData = MarketData.empty(VAL_DATE);

                AtomicBoolean shouldNeverComplete    = new AtomicBoolean();
                AtomicBoolean interrupted            = new AtomicBoolean();
                AtomicReference <Exception> thrown   = new AtomicReference <Exception>();
                ResultsListener             listener = new ResultsListener();
                test.calculateAsync(tasks, marketData, REF_DATA, listener);
                System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
                Thread thread = new Thread(() =>
                {
                    try
                    {
                        listener.result();
                        shouldNeverComplete.set(true);
                    }
                    catch (Exception ex)
                    {
                        interrupted.set(Thread.CurrentThread.Interrupted);
                        thrown.set(ex);
                    }
                    latch.Signal();
                });
                // run the thread, wait until properly started, then interrupt, wait until properly handled
                thread.Start();
                while (!fn.started)
                {
                }
                thread.Interrupt();
                latch.await();
                // asserts
                assertEquals(interrupted.get(), true);
                assertEquals(shouldNeverComplete.get(), false);
                assertEquals(thrown.get() is Exception, true);
                assertEquals(thrown.get().Cause is InterruptedException, true);
            }
            finally
            {
                executor.shutdownNow();
            }
        }
 public void onEvent(string remoteAddr, Connection conn)
 {
     Assert.NotNull(remoteAddr);
     doCheckConnection(conn);
     this.remoteAddr = remoteAddr;
     this.connection = conn;
     connected.set(true);
     connectTimes.incrementAndGet();
     if (!latch.IsSet)
     {
         latch.Signal();
     }
 }