//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void failedInstanceShouldReceiveCorrectCoordinatorIdUponRejoiningCluster() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void FailedInstanceShouldReceiveCorrectCoordinatorIdUponRejoiningCluster() { // Given HighlyAvailableGraphDatabase initialMaster = _cluster.Master; // When _cluster.shutdown(initialMaster); _cluster.await(masterAvailable(initialMaster)); _cluster.await(masterSeesSlavesAsAvailable(1)); // create node on new master to ensure that it has the greatest tx id CreateNodeOn(_cluster.Master); _cluster.sync(); LifeSupport life = new LifeSupport(); ClusterClientModule clusterClient = NewClusterClient(life, new InstanceId(1)); Cleanup.add(life); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<org.neo4j.cluster.InstanceId> coordinatorIdWhenReJoined = new java.util.concurrent.atomic.AtomicReference<>(); AtomicReference <InstanceId> coordinatorIdWhenReJoined = new AtomicReference <InstanceId>(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); clusterClient.ClusterClient.addClusterListener(new ClusterListener_AdapterAnonymousInnerClass(this, coordinatorIdWhenReJoined, latch)); life.Start(); // Then assertTrue(latch.await(20, SECONDS)); assertEquals(new InstanceId(2), coordinatorIdWhenReJoined.get()); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldHaveConfigurableJettyThreadPoolSize() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldHaveConfigurableJettyThreadPoolSize() { Jetty9WebServer server = new Jetty9WebServer(NullLogProvider.Instance, Config.defaults(), NetworkConnectionTracker.NO_OP); int numCores = 1; int configuredMaxThreads = 12; // 12 is the new min max Threads value, for one core int acceptorThreads = 1; // In this configuration, 1 thread will become an acceptor... int selectorThreads = 1; // ... and 1 thread will become a selector... int jobThreads = configuredMaxThreads - acceptorThreads - selectorThreads; // ... and the rest are job threads server.MaxThreads = numCores; server.HttpAddress = new ListenSocketAddress("localhost", 0); try { server.Start(); QueuedThreadPool threadPool = ( QueuedThreadPool )server.Jetty.ThreadPool; threadPool.start(); System.Threading.CountdownEvent startLatch = new System.Threading.CountdownEvent(jobThreads); System.Threading.CountdownEvent endLatch = LoadThreadPool(threadPool, configuredMaxThreads + 1, startLatch); startLatch.await(); // Wait for threadPool to create threads int threads = threadPool.Threads; assertEquals("Wrong number of threads in pool", configuredMaxThreads, threads); endLatch.Signal(); } finally { server.Stop(); } }
public Crawler(int numFrontQueues, int numBackQueues, TimeSpan timebetweenVisits, TimeSpan maxAgeOfRobots, IEnumerable<PrettyURL> seed, ConcurrentQueue<Tuple<PrettyURL, string, DateTime>> queue, System.Threading.CountdownEvent cte) { Robot_IAm = new RobotsStuff(maxAgeOfRobots); Mercator_IAm = new Mercator(numFrontQueues, numBackQueues, timebetweenVisits, seed); CrawledQueue = queue; CTE = cte; }
public virtual void test_combineFuturesAsMap_exception() { CompletableFuture <string> future1 = new CompletableFuture <string>(); future1.complete("A"); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); CompletableFuture <string> future2 = CompletableFuture.supplyAsync(() => { try { latch.await(); } catch (InterruptedException) { } throw new System.InvalidOperationException("Oops"); }); IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2); CompletableFuture <IDictionary <string, string> > test = Guavate.combineFuturesAsMap(input); assertEquals(test.Done, false); latch.Signal(); assertThrows(typeof(CompletionException), () => test.join()); assertEquals(test.Done, true); assertEquals(test.CompletedExceptionally, true); }
private void SendCommandASynch() { countDown = new System.Threading.CountdownEvent(1); foreach (DataGridViewRow row in dgvComputers.Rows) { if (!_closing && !_wrongCrendentialsWatcher.IsAbortRequested) { countDown.AddCount(); CommandParameters parameters = GetCommonParameters(); parameters.Row = row; parameters.TargetComputer = (ADComputer)row.Cells["ADComputer"].Value; parameters.Login = _login; parameters.Password = _password; System.Threading.ThreadPool.QueueUserWorkItem(SendCommandToComputer, (object)parameters); } } countDown.Signal(); countDown.Wait(5000 * dgvComputers.Rows.Count); DisplayProgress(); Action action = () => { dgvComputers.Sort(dgvComputers.Columns["Result"], ListSortDirection.Descending); btnClose.Enabled = true; btnAbort.Enabled = false; }; if (!_closing) { this.Invoke(action); } }
public virtual void test_toCombinedFutureMap() { CompletableFuture <string> future1 = new CompletableFuture <string>(); future1.complete("A"); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); CompletableFuture <string> future2 = CompletableFuture.supplyAsync(() => { try { latch.await(); } catch (InterruptedException) { } return("B"); }); IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2); //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: CompletableFuture <IDictionary <string, string> > test = input.SetOfKeyValuePairs().collect(Guavate.toCombinedFutureMap()); assertEquals(test.Done, false); latch.Signal(); IDictionary <string, string> combined = test.join(); assertEquals(test.Done, true); assertEquals(combined.Count, 2); assertEquals(combined["a"], "A"); assertEquals(combined["b"], "B"); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private static void await(java.util.concurrent.CountDownLatch latch) throws InterruptedException private static void Await(System.Threading.CountdownEvent latch) { if (!latch.await(1, TimeUnit.MINUTES)) { fail("Count down did not happen"); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldMutexAccessBetweenInvalidateAndinstance() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldMutexAccessBetweenInvalidateAndinstance() { // GIVEN //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger initCalls = new java.util.concurrent.atomic.AtomicInteger(); AtomicInteger initCalls = new AtomicInteger(); LazySingleReference <int> @ref = new LazySingleReferenceAnonymousInnerClass2(this, latch, initCalls); Future <int> t1Evaluate = _t1.executeDontWait(Evaluate(@ref)); _t1.waitUntilWaiting(); // WHEN Future <Void> t2Invalidate = _t2.executeDontWait(Invalidate(@ref)); _t2.waitUntilBlocked(); latch.Signal(); int e = t1Evaluate.get(); t2Invalidate.get(); // THEN assertEquals("Evaluation", 1, e); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition() { // GIVEN System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); try { Locks_Client client = NewWaitingLocksClient(latch); MasterImpl master = NewMasterWithLocksClient(client); HandshakeResult handshake = master.Handshake(1, newStoreIdForCurrentVersion()).response(); // WHEN RequestContext context = new RequestContext(handshake.Epoch(), 1, 2, 0, 0); master.NewLockSession(context); Future <Void> acquireFuture = OtherThread.execute(state => { master.AcquireExclusiveLock(context, ResourceTypes.NODE, 1L); return(null); }); OtherThread.get().waitUntilWaiting(); master.EndLockSession(context, false); verify(client).stop(); verify(client, never()).close(); latch.Signal(); acquireFuture.get(); // THEN verify(client).close(); } finally { latch.Signal(); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndexWhereLogHasRotated() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndexWhereLogHasRotated() { // Given StartDb(); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); when(_mockedIndexProvider.getPopulator(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig)), any())).thenReturn(IndexPopulatorWithControlledCompletionTiming(latch)); CreateIndex(_myLabel); RotateLogsAndCheckPoint(); // And Given Future <Void> killFuture = KillDbInSeparateThread(); latch.Signal(); killFuture.get(); latch = new System.Threading.CountdownEvent(1); when(_mockedIndexProvider.getPopulator(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig)), any())).thenReturn(IndexPopulatorWithControlledCompletionTiming(latch)); when(_mockedIndexProvider.getInitialState(any(typeof(StoreIndexDescriptor)))).thenReturn(InternalIndexState.POPULATING); // When StartDb(); // Then assertThat(getIndexes(_db, _myLabel), inTx(_db, hasSize(1))); assertThat(getIndexes(_db, _myLabel), inTx(_db, haveState(_db, Org.Neo4j.Graphdb.schema.Schema_IndexState.Populating))); verify(_mockedIndexProvider, times(2)).getPopulator(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig)), any()); verify(_mockedIndexProvider, never()).getOnlineAccessor(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig))); latch.Signal(); }
public AbstractComponentSwitcherAnonymousInnerClass(HighAvailabilityMemberStateMachineTest outerInstance, UnknownType mock, DelegateInvocationHandler <Master> handler, System.Threading.CountdownEvent latch, AtomicReference <Master> @ref) : base(mock) { this.outerInstance = outerInstance; this._handler = handler; this._latch = latch; this.@ref = @ref; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testMasterElectionAfterMasterRecoversInSlaveOnlyCluster() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void TestMasterElectionAfterMasterRecoversInSlaveOnlyCluster() { ClusterManager.ManagedCluster cluster = ClusterRule.startCluster(); assertThat(cluster.GetServerId(cluster.Master), equalTo(new InstanceId(3))); HighlyAvailableGraphDatabase master = cluster.Master; System.Threading.CountdownEvent masterFailedLatch = CreateMasterFailLatch(cluster); ClusterManager.RepairKit repairKit = cluster.Fail(master); try { assertTrue(masterFailedLatch.await(60, TimeUnit.SECONDS)); } finally { repairKit.Repair(); } cluster.Await(allSeesAllAsAvailable()); long nodeId = CreateNodeWithPropertyOn(cluster.AnySlave, PROPERTY, VALUE); using (Transaction ignore = master.BeginTx()) { assertThat(master.GetNodeById(nodeId).getProperty(PROPERTY), equalTo(VALUE)); } }
//------------------------------------------------------------------------- public virtual void test_combineFuturesAsMap() { CompletableFuture <string> future1 = new CompletableFuture <string>(); future1.complete("A"); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); CompletableFuture <string> future2 = CompletableFuture.supplyAsync(() => { try { latch.await(); } catch (InterruptedException) { } return("B"); }); IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2); CompletableFuture <IDictionary <string, string> > test = Guavate.combineFuturesAsMap(input); assertEquals(test.Done, false); latch.Signal(); IDictionary <string, string> combined = test.join(); assertEquals(test.Done, true); assertEquals(combined.Count, 2); assertEquals(combined["a"], "A"); assertEquals(combined["b"], "B"); }
internal virtual void Initialize(int numberOfUpdateTrackers) { UpdateTrackerCompletionLatch = new System.Threading.CountdownEvent(numberOfUpdateTrackers); if (numberOfUpdateTrackers > 0) { Barrier = new Org.Neo4j.Test.Barrier_Control(); } }
public ClusterMemberListener_AdapterAnonymousInnerClass(ClusterTopologyChangesIT outerInstance, Org.Neo4j.Kernel.ha.HighlyAvailableGraphDatabase newSlave1, Org.Neo4j.Kernel.ha.HighlyAvailableGraphDatabase newSlave2, System.Threading.CountdownEvent slave1Unavailable, System.Threading.CountdownEvent slave2Unavailable) { this.outerInstance = outerInstance; this._newSlave1 = newSlave1; this._newSlave2 = newSlave2; this._slave1Unavailable = slave1Unavailable; this._slave2Unavailable = slave2Unavailable; }
public HeartbeatListener_AdapterAnonymousInnerClass(ClusterTopologyChangesIT outerInstance, Org.Neo4j.Kernel.ha.HighlyAvailableGraphDatabase slave1, Org.Neo4j.Kernel.ha.HighlyAvailableGraphDatabase slave2, System.Threading.CountdownEvent slave1Left, System.Threading.CountdownEvent slave2Left) { this.outerInstance = outerInstance; this._slave1 = slave1; this._slave2 = slave2; this._slave1Left = slave1Left; this._slave2Left = slave2Left; }
internal SharedDiscoveryService() { _coreMembers = new ConcurrentDictionary <MemberId, CoreServerInfo>(); _readReplicas = new ConcurrentDictionary <MemberId, ReadReplicaInfo>(); _listeningClients = new CopyOnWriteArrayList <SharedDiscoveryCoreClient>(); _clusterIdDbNames = new ConcurrentDictionary <string, ClusterId>(); _leaderMap = new ConcurrentDictionary <string, LeaderInfo>(); _enoughMembers = new System.Threading.CountdownEvent(MIN_DISCOVERY_MEMBERS); }
public override void TearDownPageCache(MuninnPageCache pageCache) { if (BackgroundFlushLatch != null) { BackgroundFlushLatch.Signal(); BackgroundFlushLatch = null; } pageCache.Close(); _allocator.close(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void startMonitoringWhenLifecycleStarting() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void StartMonitoringWhenLifecycleStarting() { System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); FileWatcher watcher = new TestFileWatcher(latch); DefaultFileSystemWatcherService service = new DefaultFileSystemWatcherService(_jobScheduler, watcher); service.Init(); service.Start(); latch.await(); }
private void SendCommandToComputer(object data) { ADComputer computer = null; DataForComputer dataForComputer = (DataForComputer)data; DataGridViewRow row = dataForComputer.Row; String[] options = dataForComputer.Options; System.Threading.CountdownEvent countDown = dataForComputer.CountDown; try { Action startAction = () => { lock (dtGrvComputers) { if (!_closing && !_aborting) { row.Cells["Status"].Value = resMan.GetString("SendingCommand"); computer = (ADComputer)row.Cells["Computer"].Value; } } Logger.Write("Will try to send InstallPendingUpdates on : " + computer.Name); }; if (!_closing && !_aborting) { this.Invoke(startAction); } ADComputer.InstallPendingUpdatesResult result = ADComputer.InstallPendingUpdatesResult.FailToSendCommand; if (!_closing && !_aborting) { result = computer.InstallPendingUpdates(options, Username, Password); } Action endAction = () => { Logger.Write("Result for " + computer.Name + " is : " + result.ToString()); lock (dtGrvComputers) { if (!_closing && !_aborting) { row.Cells["Status"].Value = resMan.GetString(result.ToString()); } } }; if (!_closing && !_aborting) { this.Invoke(endAction); } } catch (Exception) { } finally { countDown.Signal(); } }
private void StartResetSusClientID() { System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Properties.Settings.Default.Language); Credentials cred = Credentials.GetInstance(); if (dtGrdVResult.SelectedRows.Count != 0) { if (cred.InitializeCredential() == false) { return; } } Logger.Write(lblCredentials); Action startAction = () => { lblCredentials.Text = cred.CredentialNotice; }; if (!_closing) { this.Invoke(startAction); } System.Threading.CountdownEvent countEvent = new System.Threading.CountdownEvent(1); foreach (DataGridViewRow row in dtGrdVResult.SelectedRows) { countEvent.AddCount(); ASyncClientParameters parameters = new ASyncClientParameters(); parameters.RowIndex = row.Index; parameters.Login = cred.Login; parameters.Password = cred.Password; parameters.CountEvent = countEvent; if (!_closing & !_aborting) { System.Threading.ThreadPool.QueueUserWorkItem(ResetSusClientID, parameters); } } countEvent.Signal(); countEvent.Wait(10000 * dtGrdVResult.SelectedRows.Count); if (!_closing && !_aborting) { SearchDuplicateWsusClientID(); } Action endAction = () => { ChangeUIAccess(true); }; if (!_closing) { this.Invoke(endAction); } }
//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 org.neo4j.kernel.impl.locking.Locks_Client newWaitingLocksClient(final java.util.concurrent.CountDownLatch latch) private Locks_Client NewWaitingLocksClient(System.Threading.CountdownEvent latch) { Locks_Client client = mock(typeof(Locks_Client)); doAnswer(invocation => { latch.await(); return(null); }).when(client).acquireExclusive(eq(LockTracer.NONE), any(typeof(ResourceType)), anyLong()); return(client); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private <T extends org.neo4j.graphdb.PropertyContainer> Resource<T> test(System.Func<T> setup, String... queries) throws InterruptedException, java.util.concurrent.ExecutionException private Resource <T> Test <T>(System.Func <T> setup, params string[] queries) where T : Org.Neo4j.Graphdb.PropertyContainer { System.Threading.CountdownEvent resourceLocked = new System.Threading.CountdownEvent(1); System.Threading.CountdownEvent listQueriesLatch = new System.Threading.CountdownEvent(1); System.Threading.CountdownEvent finishQueriesLatch = new System.Threading.CountdownEvent(1); T resource; using (Transaction tx = _db.beginTx()) { resource = setup(); tx.Success(); } _threads.execute(parameter => { using (Transaction tx = _db.beginTx()) { tx.AcquireWriteLock(resource); resourceLocked.Signal(); listQueriesLatch.await(); } return(null); }, null); resourceLocked.await(); _threads.executeAndAwait(parameter => { try { using (Transaction tx = _db.beginTx()) { foreach (string query in queries) { _db.execute(query).close(); } tx.Success(); } } catch (Exception t) { Console.WriteLine(t.ToString()); Console.Write(t.StackTrace); throw new Exception(t); } finally { finishQueriesLatch.Signal(); } return(null); }, null, waitingWhileIn(typeof(GraphDatabaseFacade), "execute"), SECONDS_TIMEOUT, SECONDS); return(new Resource <T>(listQueriesLatch, finishQueriesLatch, resource)); }
private System.Threading.CountdownEvent CreateMasterFailLatch(ClusterManager.ManagedCluster cluster) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch failedLatch = new java.util.concurrent.CountDownLatch(2); System.Threading.CountdownEvent failedLatch = new System.Threading.CountdownEvent(2); foreach (HighlyAvailableGraphDatabase db in cluster.AllMembers) { if (!Db.Master) { Db.DependencyResolver.resolveDependency(typeof(ClusterClient)).addHeartbeatListener(new HeartbeatListenerAnonymousInnerClass(this, failedLatch)); } } return(failedLatch); }
private static void Await(System.Threading.CountdownEvent latch) { try { bool result = latch.await(30, TimeUnit.SECONDS); if (!result) { throw new Exception("Count down did not happen. Current count: " + latch.CurrentCount); } } catch (InterruptedException e) { throw new Exception(e); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = 3000) public void conversationCanNotBeStoppedAndClosedConcurrently() throws InterruptedException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ConversationCanNotBeStoppedAndClosedConcurrently() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch answerLatch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent answerLatch = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch stopLatch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent stopLatch = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch stopReadyLatch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent stopReadyLatch = new System.Threading.CountdownEvent(1); const int sleepTime = 1000; doAnswer(invocation => { stopReadyLatch.Signal(); stopLatch.await(); TimeUnit.MILLISECONDS.sleep(sleepTime); return(null); }).when(_client).stop(); doAnswer(invocation => { answerLatch.Signal(); return(null); }).when(_client).close(); ThreadingRule.execute(_conversation => { _conversation.stop(); return(null); }, _conversation); stopReadyLatch.await(); ThreadingRule.execute(_conversation => { _conversation.close(); return(null); }, _conversation); long raceStartTime = DateTimeHelper.CurrentUnixTimeMillis(); stopLatch.Signal(); answerLatch.await(); // execution time should be at least 1000 millis long executionTime = DateTimeHelper.CurrentUnixTimeMillis() - raceStartTime; assertTrue(string.Format("Execution time should be at least equal to {0:D}, but was {1:D}.", sleepTime, executionTime), executionTime >= sleepTime); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = 60_000) public void possibleToShutdownDbWhenItIsNotHealthyAndNotAllTransactionsAreApplied() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void PossibleToShutdownDbWhenItIsNotHealthyAndNotAllTransactionsAreApplied() { // adversary that makes page cache throw exception when node store is used ClassGuardedAdversary adversary = new ClassGuardedAdversary(new CountingAdversary(1, true), typeof(NodeStore)); adversary.Disable(); GraphDatabaseService db = AdversarialPageCacheGraphDatabaseFactory.create(_fs, adversary).newEmbeddedDatabaseBuilder(_testDir.databaseDir()).newGraphDatabase(); System.Threading.CountdownEvent txStartLatch = new System.Threading.CountdownEvent(1); System.Threading.CountdownEvent txCommitLatch = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.concurrent.Future<?> result = java.util.concurrent.ForkJoinPool.commonPool().submit(() -> Future <object> result = ForkJoinPool.commonPool().submit(() => { using (Transaction tx = Db.beginTx()) { txStartLatch.Signal(); Db.createNode(); Await(txCommitLatch); tx.success(); } }); Await(txStartLatch); adversary.Enable(); txCommitLatch.Signal(); try { result.get(); fail("Exception expected"); } catch (ExecutionException ee) { // transaction is expected to fail because write through the page cache fails assertThat(ee.InnerException, instanceOf(typeof(TransactionFailureException))); } adversary.Disable(); // shutdown should complete without any problems Db.shutdown(); }
private static long[] MergeAll(long[] output, LinkedList <int> bounds) { var buffer = new long[output.Count()]; while (bounds.Count > 2) { var tmp_src = output; var tmp_buf = buffer; var w_node = bounds.First.Next; var w_copy = (bounds.Count - 1) % 2 == 1; int merges = (bounds.Count - 1) / 2; var counter = new System.Threading.CountdownEvent(merges); while (merges > 0) { System.Threading.ThreadPool.QueueUserWorkItem( w => { MergeTwo(tmp_src, tmp_buf, (MergeWindow)w); counter.Signal(); }, new MergeWindow(w_node) ); var w_next = w_node.Next.Next; bounds.Remove(w_node); w_node = w_next; merges--; } if (w_copy) { var w_prev = w_node.Previous; Array.Copy(tmp_src, w_prev.Value, tmp_buf, w_prev.Value, w_node.Value - w_prev.Value); } counter.Wait(); output = tmp_buf; buffer = tmp_src; } return(output); }
private IEnumerable RunChildren() { int childCount = Children.Count; if (childCount == 0) { throw new InvalidOperationException("RunChildren called but item has no children"); } _childTestCountdown = new CountdownEvent(childCount); foreach (UnityWorkItem child in Children) { if (CheckForCancellation()) { yield break; } var unityTestExecutionContext = new UnityTestExecutionContext(Context); child.InitializeContext(unityTestExecutionContext); var enumerable = child.Execute().GetEnumerator(); while (true) { if (!enumerable.MoveNext()) { break; } ResultedInDomainReload |= child.ResultedInDomainReload; yield return(enumerable.Current); } _suiteResult.AddResult(child.Result); childCount--; } if (childCount > 0) { while (childCount-- > 0) { CountDownChildTest(); } } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void closeClientAfterLockStopped(boolean shared) throws Exception private void CloseClientAfterLockStopped(bool shared) { AcquiredLock thisThreadsExclusiveLock = AcquireExclusiveLockInThisThread(); System.Threading.CountdownEvent firstLockAcquired = new System.Threading.CountdownEvent(1); LockAcquisition acquisition = TryAcquireTwoLocksLockInAnotherThread(shared, firstLockAcquired); Await(firstLockAcquired); AssertThreadIsWaitingForLock(acquisition); AssertLocksHeld(FIRST_NODE_ID, SECOND_NODE_ID); acquisition.Stop(); AssertLockAcquisitionFailed(acquisition); AssertLocksHeld(FIRST_NODE_ID); thisThreadsExclusiveLock.Release(); AssertNoLocksHeld(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: private void acquireLockAfterOtherLockStoppedSameThread(boolean firstLockShared, boolean secondLockShared) throws Exception private void AcquireLockAfterOtherLockStoppedSameThread(bool firstLockShared, bool secondLockShared) { AcquiredLock thisThreadsExclusiveLock = AcquireExclusiveLockInThisThread(); System.Threading.CountdownEvent firstLockFailed = new System.Threading.CountdownEvent(1); System.Threading.CountdownEvent startSecondLock = new System.Threading.CountdownEvent(1); LockAcquisition lockAcquisition = AcquireTwoLocksInAnotherThread(firstLockShared, secondLockShared, firstLockFailed, startSecondLock); AssertThreadIsWaitingForLock(lockAcquisition); lockAcquisition.Stop(); Await(firstLockFailed); thisThreadsExclusiveLock.Release(); startSecondLock.Signal(); AssertLockAcquisitionSucceeded(lockAcquisition); }
public static double[] ETCToPTC(double[][] Octave_ETC, double CutOffTime, int sample_frequency_in, int sample_frequency_out, double Rho_C) { int length = 4096; double[] IR = new double[(int)Math.Floor(sample_frequency_out * CutOffTime) + (int)length]; double BW = (double)sample_frequency_out / (double)sample_frequency_in; //Convert to Pressure & Interpolate full resolution IR int ct = 0; System.Threading.Semaphore S = new System.Threading.Semaphore(0, 1); S.Release(1); double[] time = new double[(int)Math.Floor(sample_frequency_out * CutOffTime) + (int)length]; double dt = 1f/(float)sample_frequency_out; for (int i = 0; i < time.Length; i++) { time[i] = i * dt; } int proc = UI.PachydermAc_PlugIn.Instance.ProcessorSpec(); double[][] output = new double[proc][]; double[][] samplep = new double[proc][]; System.Threading.Thread[] T = new System.Threading.Thread[proc]; int[] to = new int[proc]; int[] from = new int[proc]; System.Threading.CountdownEvent CDE = new System.Threading.CountdownEvent(Octave_ETC[0].Length); for (int p = 0; p < proc; p++) { output[p] = new double[length]; samplep[p] = new double[length * 2]; to[p] = p * Octave_ETC[0].Length / proc; from[p] = (p + 1) * Octave_ETC[0].Length / proc; T[p] = new System.Threading.Thread((thread) => { int thr = (int)thread; for (int t = to[thr]; t < from[thr]; t++) { ct++; double[] pr = new double[8]; for (int oct = 0; oct < 8; oct++) pr[oct] = Math.Sqrt(Octave_ETC[oct][t] * Rho_C); double sum = 0; foreach (double d in pr) sum += d; if (sum > 0) { output[thr] = Filter.Signal(pr, sample_frequency_out, 4096, thr); //Audio.Pach_SP.Raised_Cosine_Window(ref output[thr]); for (int k = 0; k < length; k++) { IR[(int)Math.Floor(t * BW) + k] += output[thr][k]; } } CDE.Signal(); } }); T[p].Start(p); } ProgressBox VB = new ProgressBox("Signal Production Progress"); VB.Show(); do { if (CDE.IsSet) { break; } VB.Populate((int)(100 * (1f - ((float)CDE.CurrentCount / (float)IR.Length)))); System.Threading.Thread.Sleep(500); } while (true); //CDE.Wait(); VB.Close(); return IR; }
public void TestRunTwoExperimentsSimultanouslyAndTerminateOneExperiment() { //assure workspace is empty AppContext.WorkspaceInstance.Clear(); var done = new System.Threading.CountdownEvent(2); //start experiment one (takes more than 2 seconds to finish successfully) Experiment experimentOne = LoadExperiment("long-experiment.teml"); MockProgress progressOne = new MockProgress(); experimentOne.RunExperiment(progressOne, AppContext.WorkspaceInstance, AppContext.Components); experimentOne.ExperimentCompleted += (sender, args) => { done.Signal(); }; //start experiment two and terminate it MockProgress progressTwo = new MockProgress(); Experiment experimentTwo = LoadExperiment("infinite_loop_terminate_experiment_test.teml"); experimentTwo.RunExperiment(progressTwo, AppContext.WorkspaceInstance, AppContext.Components); experimentTwo.ExperimentStarted += (sender, args) => { experimentTwo.StopRunningExperiment(); }; experimentTwo.ExperimentCompleted += (sender, args) => { done.Signal(); }; //wait for both experiment to end done.Wait(5000); //the experiment one should have ended successfully (it SHOULD NOT have been terminated) Assert.IsFalse(progressOne.HasError); Assert.AreEqual(Messages.ExperimentRunnerSuccessMessage, progressOne.CurrentStatus); //while exepriment two should be terminated Assert.IsTrue(progressTwo.HasError); Assert.AreEqual(Messages.ExperimentExecutionTerminated, progressTwo.CurrentStatus); }