//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void oneOrTheOtherShouldDeadlock() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void OneOrTheOtherShouldDeadlock() { AtomicInteger deadlockCount = new AtomicInteger(); HighlyAvailableGraphDatabase master = _cluster.Master; Node masterA = CreateNodeOnMaster(_testLabel, master); Node masterB = CreateNodeOnMaster(_testLabel, master); HighlyAvailableGraphDatabase slave = _cluster.AnySlave; using (Transaction transaction = slave.BeginTx()) { Node slaveA = slave.GetNodeById(masterA.Id); Node slaveB = slave.GetNodeById(masterB.Id); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); transaction.AcquireWriteLock(slaveB); Thread masterTx = new Thread(() => { try { using (Transaction tx = master.BeginTx()) { tx.acquireWriteLock(masterA); latch.Signal(); tx.acquireWriteLock(masterB); } } catch (DeadlockDetectedException) { deadlockCount.incrementAndGet(); } }); masterTx.Start(); latch.await(); try { transaction.AcquireWriteLock(slaveA); } catch (DeadlockDetectedException) { deadlockCount.incrementAndGet(); } masterTx.Join(); } assertEquals(1, deadlockCount.get()); }
public virtual void test_poll_exception() { AtomicInteger counter = new AtomicInteger(); System.Func <string> pollingFn = () => { switch (counter.incrementAndGet()) { case 1: return(null); case 2: throw new System.InvalidOperationException("Expected"); default: throw new AssertionError("Test failed"); } }; ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try { CompletableFuture <string> future = Guavate.poll(executor, Duration.ofMillis(100), Duration.ofMillis(100), pollingFn); assertThrows(() => future.join(), typeof(CompletionException), "java.lang.IllegalStateException: Expected"); } finally { executor.shutdown(); } }
public MuninnPageCache(PageSwapperFactory swapperFactory, MemoryAllocator memoryAllocator, int cachePageSize, PageCacheTracer pageCacheTracer, PageCursorTracerSupplier pageCursorTracerSupplier, VersionContextSupplier versionContextSupplier, JobScheduler jobScheduler) { VerifyHacks(); VerifyCachePageSizeIsPowerOfTwo(cachePageSize); int maxPages = CalculatePageCount(memoryAllocator, cachePageSize); // Expose the total number of pages pageCacheTracer.MaxPages(maxPages); MemoryAllocationTracker memoryTracker = GlobalMemoryTracker.INSTANCE; this._pageCacheId = _pageCacheIdCounter.incrementAndGet(); this._swapperFactory = swapperFactory; this._cachePageSize = cachePageSize; this._keepFree = Math.Min(_pagesToKeepFree, maxPages / 2); this._pageCacheTracer = pageCacheTracer; this._pageCursorTracerSupplier = pageCursorTracerSupplier; this._versionContextSupplier = versionContextSupplier; this._printExceptionsOnClose = true; long alignment = swapperFactory.RequiredBufferAlignment; this.VictimPage = VictimPageReference.GetVictimPage(cachePageSize, memoryTracker); this.Pages = new PageList(maxPages, cachePageSize, memoryAllocator, new SwapperSet(), VictimPage, alignment); this._scheduler = jobScheduler; FreelistHead = new AtomicInteger(); }
//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 recurringJobWithExceptionShouldKeepRunning() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void RecurringJobWithExceptionShouldKeepRunning() { // given RobustJobSchedulerWrapper robustWrapper = new RobustJobSchedulerWrapper(_actualScheduler, _log); AtomicInteger count = new AtomicInteger(); System.InvalidOperationException e = new System.InvalidOperationException(); // when int nRuns = 100; JobHandle jobHandle = robustWrapper.ScheduleRecurring(Group.HZ_TOPOLOGY_REFRESH, 1, () => { if (count.get() < nRuns) { count.incrementAndGet(); throw e; } }); // then assertEventually("run count", count.get, Matchers.equalTo(nRuns), _defaultTimeoutMs, MILLISECONDS); jobHandle.Cancel(true); verify(_log, timeout(_defaultTimeoutMs).times(nRuns)).warn("Uncaught exception", e); }
//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); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void createdWorkerThreadsShouldContainConnectorName() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void CreatedWorkerThreadsShouldContainConnectorName() { AtomicInteger executeBatchCompletionCount = new AtomicInteger(); AtomicReference <Thread> poolThread = new AtomicReference <Thread>(); AtomicReference <string> poolThreadName = new AtomicReference <string>(); string id = System.Guid.randomUUID().ToString(); BoltConnection connection = NewConnection(id); when(connection.HasPendingJobs()).thenAnswer(inv => { executeBatchCompletionCount.incrementAndGet(); return(false); }); when(connection.ProcessNextBatch()).thenAnswer(inv => { poolThread.set(Thread.CurrentThread); poolThreadName.set(Thread.CurrentThread.Name); return(true); }); _boltScheduler.start(); _boltScheduler.created(connection); _boltScheduler.enqueued(connection, Jobs.noop()); Predicates.await(() => executeBatchCompletionCount.get() > 0, 1, MINUTES); assertThat(poolThread.get().Name, not(equalTo(poolThreadName.get()))); assertThat(poolThread.get().Name, containsString(string.Format("[{0}]", CONNECTOR_KEY))); assertThat(poolThread.get().Name, not(containsString(string.Format("[{0}]", connection.RemoteAddress())))); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public Object handleRequest(com.alipay.remoting.BizContext bizCtx, com.alipay.remoting.rpc.common.RequestBody request) throws Exception public override object handleRequest(BizContext bizCtx, object request) { string threadName = Thread.CurrentThread.Name; Assert.Contains("Rpc-specific1-executor", threadName); logger.LogWarning("Request received:" + request); Assert.Equal(typeof(RequestBody), request.GetType()); long waittime = ((long?)bizCtx.InvokeContext.get(InvokeContext.BOLT_PROCESS_WAIT_TIME)).Value; logger.LogWarning("Client User processor process wait time [" + waittime + "]."); invokeTimes.incrementAndGet(); if (!delaySwitch) { return(RequestBody.DEFAULT_CLIENT_RETURN_STR); } try { Thread.Sleep(delayMs); } catch (ThreadInterruptedException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } return(RequestBody.DEFAULT_CLIENT_RETURN_STR); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldKeepHighestDuringConcurrentOfferings() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldKeepHighestDuringConcurrentOfferings() { // GIVEN //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final HighestTransactionId highest = new HighestTransactionId(-1, -1, -1); HighestTransactionId highest = new HighestTransactionId(-1, -1, -1); Race race = new Race(); int updaters = max(2, Runtime.availableProcessors()); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger accepted = new java.util.concurrent.atomic.AtomicInteger(); AtomicInteger accepted = new AtomicInteger(); for (int i = 0; i < updaters; i++) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final long id = i + 1; long id = i + 1; race.AddContestant(() => { if (highest.Offer(id, id, id)) { accepted.incrementAndGet(); } }); } // WHEN race.Go(); // THEN assertTrue(accepted.get() > 0); assertEquals(updaters, highest.Get().transactionId()); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = 10_000) public void scheduledTasksThatThrowsMustPropagateException() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ScheduledTasksThatThrowsMustPropagateException() { CentralJobScheduler scheduler = new CentralJobScheduler(); scheduler.Init(); Exception boom = new Exception("boom"); AtomicInteger triggerCounter = new AtomicInteger(); ThreadStart job = () => { triggerCounter.incrementAndGet(); throw boom; }; JobHandle handle = scheduler.ScheduleRecurring(Group.INDEX_POPULATION, job, 1, TimeUnit.MILLISECONDS); try { handle.WaitTermination(); fail("waitTermination should have failed."); } catch (ExecutionException e) { assertThat(e.InnerException, @is(boom)); } }
//------------------------------------------------------------------------- public virtual void test_poll() { AtomicInteger counter = new AtomicInteger(); System.Func <string> pollingFn = () => { switch (counter.incrementAndGet()) { case 1: return(null); case 2: return("Yes"); default: throw new AssertionError("Test failed"); } }; ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); CompletableFuture <string> future = Guavate.poll(executor, Duration.ofMillis(100), Duration.ofMillis(100), pollingFn); assertEquals(future.join(), "Yes"); }
public void run() { _count.incrementAndGet(); _latch.waitForAllToStart(); _latch.finish(); }
private Answer <T> NewCountingAnswer <T>(AtomicInteger counter) { return(invocationOnMock => { counter.incrementAndGet(); return null; }); }
private static ThreadFactory NewThreadFactoryWithCounter(AtomicInteger counter) { return(job => { counter.incrementAndGet(); return Executors.defaultThreadFactory().newThread(job); }); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldNotStartOtherSamplingWhenSamplingAllTheIndexes() public virtual void ShouldNotStartOtherSamplingWhenSamplingAllTheIndexes() { // given //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger totalCount = new java.util.concurrent.atomic.AtomicInteger(0); AtomicInteger totalCount = new AtomicInteger(0); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger concurrentCount = new java.util.concurrent.atomic.AtomicInteger(0); AtomicInteger concurrentCount = new AtomicInteger(0); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.test.DoubleLatch jobLatch = new org.neo4j.test.DoubleLatch(); DoubleLatch jobLatch = new DoubleLatch(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.test.DoubleLatch testLatch = new org.neo4j.test.DoubleLatch(); DoubleLatch testLatch = new DoubleLatch(); IndexSamplingJobFactory jobFactory = (_indexId, proxy) => { if (!concurrentCount.compareAndSet(0, 1)) { throw new System.InvalidOperationException("count !== 0 on create"); } totalCount.incrementAndGet(); jobLatch.WaitForAllToStart(); testLatch.StartAndWaitForAllToStart(); jobLatch.WaitForAllToFinish(); concurrentCount.decrementAndGet(); testLatch.Finish(); return(null); }; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final IndexSamplingController controller = new IndexSamplingController(samplingConfig, jobFactory, jobQueue, tracker, snapshotProvider, scheduler, always(true)); IndexSamplingController controller = new IndexSamplingController(_samplingConfig, jobFactory, _jobQueue, _tracker, _snapshotProvider, _scheduler, Always(true)); when(_tracker.canExecuteMoreSamplingJobs()).thenReturn(true); when(_indexProxy.State).thenReturn(ONLINE); // when running once (new Thread(RunController(controller, TRIGGER_REBUILD_UPDATED))).Start(); jobLatch.StartAndWaitForAllToStart(); testLatch.WaitForAllToStart(); // then blocking on first job assertEquals(1, concurrentCount.get()); // when running a second time controller.SampleIndexes(BACKGROUND_REBUILD_UPDATED); // then no concurrent job execution jobLatch.Finish(); testLatch.WaitForAllToFinish(); // and finally exactly one job has run to completion assertEquals(0, concurrentCount.get()); assertEquals(1, totalCount.get()); }
private Answer <T> NewBlockingAnswer <T>(AtomicInteger counter, AtomicBoolean exitCondition) { return(invocationOnMock => { counter.incrementAndGet(); Predicates.awaitForever(() => Thread.CurrentThread.Interrupted || exitCondition.get(), 500, MILLISECONDS); return null; }); }
internal virtual void UpdateCounterAndAssertSingleUpdate(AtomicInteger counter) { int count = counter.incrementAndGet(); if (count > 1) { throw new System.InvalidOperationException("called new on same factory method multiple times"); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void mustNotStartRecurringTasksWherePriorExecutionHasNotYetFinished() public virtual void MustNotStartRecurringTasksWherePriorExecutionHasNotYetFinished() { ThreadStart runnable = () => { _counter.incrementAndGet(); _semaphore.acquireUninterruptibly(); }; _scheduler.submit(Group.STORAGE_MAINTENANCE, runnable, 100, 100); for (int i = 0; i < 4; i++) { _scheduler.tick(); _clock.forward(100, TimeUnit.NANOSECONDS); } _semaphore.release(int.MaxValue); _pools.getThreadPool(Group.STORAGE_MAINTENANCE).shutDown(); assertThat(_counter.get(), @is(1)); }
public override void RemoveChecked(long expectedValue) { if (expectedValue < PreviousId) { // Just to bypass the string creation every check assertTrue("Expected to remove head " + expectedValue + ", which should have been greater than previously seen id " + PreviousId, expectedValue > PreviousId); } PreviousId = expectedValue; Delegate.removeChecked(expectedValue); RemovedCount.incrementAndGet(); }
private double getEvaluation(FastByIDMap <PreferenceArray> testPrefs, Recommender recommender) { this.reset(); List <Action> callables = new List <Action>(); AtomicInteger noEstimateCounter = new AtomicInteger(); using (IEnumerator <KeyValuePair <long, PreferenceArray> > enumerator = testPrefs.entrySet().GetEnumerator()) { while (enumerator.MoveNext()) { Action item = null; KeyValuePair <long, PreferenceArray> entry = enumerator.Current; if (item == null) { item = delegate { long userID = entry.Key; PreferenceArray array = entry.Value; foreach (Preference preference in array) { float f = float.NaN; try { f = recommender.estimatePreference(userID, preference.getItemID()); } catch (NoSuchUserException) { log.info("User exists in test data but not training data: {}", new object[] { userID }); } catch (NoSuchItemException) { log.info("Item exists in test data but not training data: {}", new object[] { preference.getItemID() }); } if (float.IsNaN(f)) { noEstimateCounter.incrementAndGet(); } else { f = this.capEstimatedPreference(f); this.processOneEstimate(f, preference); } } }; } callables.Add(item); } } log.info("Beginning evaluation of {} users", new object[] { callables.Count }); RunningAverageAndStdDev timing = new FullRunningAverageAndStdDev(); execute(callables, noEstimateCounter, timing); return(this.computeFinalEvaluation()); }
/* ---- many producers ---- */ public override void Produce(T t) { _queue.add(t); int newSize = _size.incrementAndGet(); if (newSize > _maxSize) { _queue.poll(); _size.decrementAndGet(); } }
public override void Rebuilt(long roughNodeCount) { // In HA each slave database will startup with an empty database before realizing that // it needs to copy a store from its master, let alone find its master. // So we're expecting one call to this method from each slave with node count == 0. Ignore those. // We're tracking number of times we're rebuilding the index where there's data to rebuild, // i.e. after the db has been copied from the master. if (roughNodeCount > 0) { TimesRebuiltWithData.incrementAndGet(); } }
private void WriteCurrentChunk() { if (!_channel.Open || !_channel.Connected || !_channel.Bound) { throw new ComException("Channel has been closed, so no need to try to write to it anymore. Client closed it?"); } WaitForClientToCatchUpOnReadingChunks(); ChannelFuture future = _channel.write(_buffer); future.addListener(NewChannelFutureListener(_buffer)); _writeAheadCounter.incrementAndGet(); }
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(); } }
// activity ///////////////////////////////////////////////////////////////// /// <summary> /// generates an activity instance id /// </summary> protected internal override string generateActivityInstanceId(string activityId) { int nextId = idGenerator.incrementAndGet(); string compositeId = activityId + ":" + nextId; if (compositeId.Length > 64) { return(nextId.ToString()); } else { return(compositeId); } }
protected internal override void Process(RelationshipGroupRecord[] batch, BatchSender sender) { long lastOwningNode = LastBatchLastOwningNode; foreach (RelationshipGroupRecord record in batch) { assertTrue(record.OwningNode >= lastOwningNode); assertTrue(record.OwningNode > LastBatchLastOwningNode); } ProcessCounter.incrementAndGet(); if (batch.Length > 0) { LastBatchLastOwningNode = batch[batch.Length - 1].OwningNode; } }
internal virtual LocalVariable CreateNew(TypeReference type, string name) { if (_localVariables.ContainsKey(name)) { throw new System.InvalidOperationException(string.Format("Local variable {0} already in scope", name)); } LocalVariable localVariable = new LocalVariable(type, name, _counter.AndIncrement); _localVariables[name] = localVariable; //if 64 bit types we need to give it one more index if (type.SimpleName().Equals("double") || type.SimpleName().Equals("long")) { _counter.incrementAndGet(); } return(localVariable); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void successfulJobsShouldTriggerSchedulingOfPendingJobs() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void SuccessfulJobsShouldTriggerSchedulingOfPendingJobs() { AtomicInteger counter = new AtomicInteger(); string id = System.Guid.randomUUID().ToString(); BoltConnection connection = NewConnection(id); when(connection.ProcessNextBatch()).thenAnswer(inv => counter.incrementAndGet() > 0); when(connection.HasPendingJobs()).thenReturn(true).thenReturn(false); _boltScheduler.start(); _boltScheduler.created(connection); _boltScheduler.enqueued(connection, Jobs.noop()); Predicates.await(() => counter.get() > 1, 1, MINUTES); verify(connection, times(2)).processNextBatch(); }
private void OpenCall(string name) { // do not open call unless we are in STARTED if (State.Started == _state.get()) { // increment openCalls for closers to see _openCalls.incrementAndGet(); // ensure that the previous increment actually gets seen by closers if (State.Closed == _state.get()) { throw new System.InvalidOperationException("Cannot call " + name + "() after index has been closed"); } } else { throw new System.InvalidOperationException("Cannot call " + name + "() when index state is " + _state.get()); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void intVisitorShouldNotSeeEntriesAfterRequestingBreakOut() internal virtual void IntVisitorShouldNotSeeEntriesAfterRequestingBreakOut() { // GIVEN PrimitiveIntSet map = Primitive.intSet(); map.Add(1); map.Add(2); map.Add(3); map.Add(4); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger counter = new java.util.concurrent.atomic.AtomicInteger(); AtomicInteger counter = new AtomicInteger(); // WHEN map.VisitKeys(value => counter.incrementAndGet() > 2); // THEN assertThat(counter.get(), @is(3)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testCloseableScheduleWithFixedDelayAndAdditionalTasks() throws InterruptedException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void testCloseableScheduleWithFixedDelayAndAdditionalTasks() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger outerCounter = new java.util.concurrent.atomic.AtomicInteger(0); AtomicInteger outerCounter = new AtomicInteger(0); Runnable command = () => { outerCounter.incrementAndGet(); }; executorService.scheduleWithFixedDelay(command, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS); CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger innerCounter = new java.util.concurrent.atomic.AtomicInteger(0); AtomicInteger innerCounter = new AtomicInteger(0); service.scheduleWithFixedDelay(() => { innerCounter.incrementAndGet(); }, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS); Thread.Sleep(DELAY_MS * 4); service.close(); Thread.Sleep(DELAY_MS * 2); int innerValue = innerCounter.get(); Assert.assertTrue(innerValue > 0); int value = outerCounter.get(); Thread.Sleep(DELAY_MS * 2); int newValue = outerCounter.get(); Assert.assertTrue(newValue > value); Assert.assertEquals(innerValue, innerCounter.get()); value = newValue; Thread.Sleep(DELAY_MS * 2); newValue = outerCounter.get(); Assert.assertTrue(newValue > value); Assert.assertEquals(innerValue, innerCounter.get()); }