//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldKeepSmallPeakAndNeverDisposeIfAcquireAndReleaseContinuously() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldKeepSmallPeakAndNeverDisposeIfAcquireAndReleaseContinuously() { // given const int poolMinSize = 1; StatefulMonitor stateMonitor = new StatefulMonitor(this); FakeClock clock = FakeClocks; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ResourcePool<Something> pool = getResourcePool(stateMonitor, clock, poolMinSize); ResourcePool <Something> pool = GetResourcePool(stateMonitor, clock, poolMinSize); // when for (int i = 0; i < 200; i++) { IList <ResourceHolder> newOnes = AcquireFromPool(pool, 1); System.Threading.CountdownEvent release = new System.Threading.CountdownEvent(newOnes.Count); foreach (ResourceHolder newOne in newOnes) { newOne.Release(release); } release.await(); } // then assertEquals(-1, stateMonitor.CurrentPeakSize.get()); // no alarm has rung, -1 is the default assertEquals(1, stateMonitor.CreatedConflict.get()); assertEquals(0, stateMonitor.DisposedConflict.get()); // we should always be below min size, so 0 dispose calls }
public void TestChangeNotification() { var countDown = new CountdownEvent(1); EventHandler<DatabaseChangeEventArgs> handler = (sender, e) => countDown.Signal(); database.Changed += handler; // create a document var documentProperties = new Dictionary<string, object>(); documentProperties["foo"] = 1; documentProperties["bar"] = false; documentProperties["baz"] = "touch"; var body = new Body(documentProperties); var rev1 = new RevisionInternal(body); database.PutRevision(rev1, null, false); Sleep(500); Assert.IsTrue(countDown.Wait(TimeSpan.FromSeconds(1))); // Analysis disable once DelegateSubtraction database.Changed -= handler; }
internal ResourceReader( SlaveLocksClientConcurrentTest outerInstance, SlaveLocksClient locksClient, ResourceType resourceType, long id, System.Threading.CountdownEvent resourceLatch, System.Threading.CountdownEvent resourceReleaseLatch ) : base(outerInstance, locksClient, resourceType, id) { this._outerInstance = outerInstance; this.ResourceLatch = resourceLatch; this.ResourceReleaseLatch = resourceReleaseLatch; }
static void Main(string[] args) { // If using an API key //ImportIO io = new ImportIO("http://api.import.io",Guid.parse("d08d14f3-6c98-44af-a301-f8d4288ecce3"),"tMFNJzaaLe8sgYF9hFNhKI7akyiPLMhfu8U2omNVCVr5hqWWLyiQMApDDyUucQKF++BAoVi6jnGnavYqRKP/9g=="); // If using a username and password ImportIO io = new ImportIO(); io.Login("xxx", "xxx"); io.Connect(); Dictionary<String,Object> query1 = new Dictionary<string,object>(); query1.Add("input",new Dictionary<String,String>() {{ "query","mac mini" }}); query1.Add("connectorGuids", new List<String>() { "39df3fe4-c716-478b-9b80-bdbee43bfbde" }); Dictionary<String, Object> query2 = new Dictionary<string, object>(); query2.Add("input", new Dictionary<String, String>() { { "query", "ubuntu" } }); query2.Add("connectorGuids", new List<String>() { "39df3fe4-c716-478b-9b80-bdbee43bfbde" }); Dictionary<String, Object> query3 = new Dictionary<string, object>(); query3.Add("input", new Dictionary<String, String>() { { "query", "ibm" } }); query3.Add("connectorGuids", new List<String>() { "39df3fe4-c716-478b-9b80-bdbee43bfbde" }); countdownLatch = new CountdownEvent(3); io.DoQuery(query1, HandleQuery); io.DoQuery(query2, HandleQuery); io.DoQuery(query3, HandleQuery); countdownLatch.Wait(); io.Disconnect(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = 3_000) public void shouldGiveUpQueueingOnStop() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldGiveUpQueueingOnStop() { // given for (int i = 1; i <= _maxBatchSize; i++) // fell the queue { _txApplier.queue(CreateTxWithId(_startTxId + i)); } // when System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); Thread thread = new Thread(() => { latch.Signal(); try { _txApplier.queue(CreateTxWithId(_startTxId + _maxBatchSize + 1)); } catch (Exception e) { throw new Exception(e); } }); thread.Start(); latch.await(); _txApplier.stop(); // then we don't get stuck thread.Join(); }
public void TestTimerStartAutoReset() { CountdownEvent cde = new CountdownEvent(1); int result = 0; _timer = new TestTimer(1); // Test defaults. Assert.Equal(1, _timer.Interval); Assert.True(_timer.AutoReset); _timer.AutoReset = false; _timer.Elapsed += (sender, e) => { result = ++result; cde.Signal(); }; _timer.Start(); Assert.True(_timer.Enabled); cde.Wait(); // Only elapsed once. Assert.Equal(1, result); cde = new CountdownEvent(10); _timer.AutoReset = true; cde.Wait(); cde.Dispose(); _timer.Stop(); // Atleast elapsed 10 times. Assert.True(result >= 10); }
public void be_able_to_subscribe_to_non_existing_stream_and_then_catch_event() { const string stream = "be_able_to_subscribe_to_non_existing_stream_and_then_catch_event"; using (var store = BuildConnection(_node)) { store.ConnectAsync().Wait(); var appeared = new CountdownEvent(1); var dropped = new CountdownEvent(1); var subscription = store.SubscribeToStreamFrom(stream, null, CatchUpSubscriptionSettings.Default, (_, x) => appeared.Signal(), _ => Log.Info("Live processing started."), (_, __, ___) => dropped.Signal()); store.AppendToStreamAsync(stream, ExpectedVersion.EmptyStream, TestEvent.NewTestEvent()).Wait(); if (!appeared.Wait(Timeout)) { Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); Assert.Fail("Appeared countdown event timed out."); } Assert.IsFalse(dropped.Wait(0)); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); } }
static void M1() { var sameLocalVariable = 123; var cdevent = new CountdownEvent(2); if (Fork.CloneThread()) { lock (_sync) { Console.ReadKey(); Console.WriteLine("in forked thread: {0}, tid: {1} ", sameLocalVariable, Thread.CurrentThread.ManagedThreadId); cdevent.Signal(); } } else { lock (_sync) { Console.ReadKey(); Console.WriteLine("in parent thread: {0}, tid: {1} ", sameLocalVariable, Thread.CurrentThread.ManagedThreadId); cdevent.Signal(); } } cdevent.Wait(); }
protected override long RunDisruptorPass() { Setup(); var latch = new CountdownEvent(NUM_EVENT_PROCESSORS); var listTh = new List<Thread>(); for (int i = 0; i < 3; i++) { handlers[i].Reset(latch, -1 + ITERATIONS); } disruptor.Start(); var start = System.Diagnostics.Stopwatch.StartNew(); for (long i = 0; i < ITERATIONS; i++) { long sequence = ringBuffer.Next(); ringBuffer[sequence].Value = i; ringBuffer.Publish(sequence); } latch.Wait(); long opsPerSecond = (ITERATIONS * 1000L) / start.ElapsedMilliseconds; for (int i = 0; i < NUM_EVENT_PROCESSORS; i++) { Assert.AreEqual(results[i], handlers[i].Value); } disruptor.Shutdown(); return opsPerSecond; }
public void be_able_to_subscribe_to_non_existing_stream() { const string stream = "be_able_to_subscribe_to_non_existing_stream"; using (var store = BuildConnection(_node)) { store.ConnectAsync().Wait(); var appeared = new ManualResetEventSlim(false); var dropped = new CountdownEvent(1); var subscription = store.SubscribeToStreamFrom(stream, null, CatchUpSubscriptionSettings.Default, (_, x) => appeared.Set(), _ => Log.Info("Live processing started."), (_, __, ___) => dropped.Signal()); Thread.Sleep(100); // give time for first pull phase store.SubscribeToStreamAsync(stream, false, (s, x) => { }, (s, r, e) => { }).Wait(); Thread.Sleep(100); Assert.IsFalse(appeared.Wait(0), "Some event appeared."); Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldSendAMessageFromAClientWhichIsReceivedByAServer() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldSendAMessageFromAClientWhichIsReceivedByAServer() { // given int port1 = PortAuthority.allocatePort(); int port2 = PortAuthority.allocatePort(); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); LifeSupport life = new LifeSupport(); Server server1 = new Server(latch, MapUtil.stringMap(ClusterSettings.cluster_server.name(), "localhost:" + port1, ClusterSettings.server_id.name(), "1", ClusterSettings.initial_hosts.name(), "localhost:" + port1 + ",localhost:" + port2)); life.Add(server1); Server server2 = new Server(latch, MapUtil.stringMap(ClusterSettings.cluster_server.name(), "localhost:" + port2, ClusterSettings.server_id.name(), "2", ClusterSettings.initial_hosts.name(), "localhost:" + port1 + ",localhost:" + port2)); life.Add(server2); life.Start(); // when server1.Process(Message.To(TestMessage.HelloWorld, URI.create("cluster://127.0.0.1:" + port2), "Hello World")); // then assertTrue(latch.await(5, TimeUnit.SECONDS)); assertTrue("server1 should have processed the message", server1.ProcessedMessage()); assertTrue("server2 should have processed the message", server2.ProcessedMessage()); life.Shutdown(); }
static void Main(string[] args) { int max = 50; CountdownEvent cd = new CountdownEvent(max); string endPoint = "tcp://localhost:5557"; System.Console.WriteLine("Publishing on {0}\n", endPoint); const string topic = "TestTopicxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; { var publisher = new MessagePublisher<IMessage>("tcp://localhost:5557", new ProtoBufMessageSerializer(), topic); for (int i = 0; i < max; i++) { publisher.PublishAsync(new Message1AndItIs32CharactersLongForSureDefinitionForSure() { Id = i }); Thread.Sleep(TimeSpan.FromSeconds(0.5)); System.Console.WriteLine("Published: {0}", i); } } System.Console.WriteLine("[finished - any key to continue]"); System.Console.ReadKey(); }
public virtual void ShouldKeepHighest() { // GIVEN Race race = new Race(); HighestId highestId = new HighestId(); int threads = Runtime.Runtime.availableProcessors(); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(threads); AtomicLongArray highestIds = new AtomicLongArray(threads); for (int c = 0; c < threads; c++) { int cc = c; race.AddContestant(new RunnableAnonymousInnerClass(this, highestId, latch, highestIds, cc)); } race.WithEndCondition(() => latch.CurrentCount == 0); // WHEN race.Go(); long highest = 0; for (int i = 0; i < threads; i++) { highest = max(highest, highestIds.get(i)); } assertEquals(highest, highestId.Get()); }
public void be_able_to_subscribe_to_empty_db() { using (var store = TestConnection.Create(_node.TcpEndPoint)) { store.ConnectAsync().Wait(); var appeared = new ManualResetEventSlim(false); var dropped = new CountdownEvent(1); var subscription = store.SubscribeToAllFrom(null, false, (_, x) => { if (!SystemStreams.IsSystemStream(x.OriginalEvent.EventStreamId)) appeared.Set(); }, _ => Log.Info("Live processing started."), (_, __, ___) => dropped.Signal()); Thread.Sleep(100); // give time for first pull phase store.SubscribeToAllAsync(false, (s, x) => { }, (s, r, e) => { }).Wait(); Thread.Sleep(100); Assert.IsFalse(appeared.Wait(0), "Some event appeared."); Assert.IsFalse(dropped.Wait(0), "Subscription was dropped prematurely."); subscription.Stop(Timeout); Assert.IsTrue(dropped.Wait(Timeout)); } }
protected PerformanceRecord ExecuteReadWithParallel(string operation, IEnumerable<uint> ids, int numberOfThreads, Func<long> readAction) { var countdownEvent = new CountdownEvent(numberOfThreads); var sw = Stopwatch.StartNew(); var bytes = new long[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { var c = i; ThreadPool.QueueUserWorkItem( state => { bytes[c] = readAction(); countdownEvent.Signal(); }); } countdownEvent.Wait(); sw.Stop(); return new PerformanceRecord { Bytes = bytes.Sum(), Operation = operation, Time = DateTime.Now, Duration = sw.ElapsedMilliseconds, ProcessedItems = ids.Count() * numberOfThreads }; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeout = 5_000) public void shouldGiveUpAddingMessagesInTheQueueIfTheHandlerHasBeenStopped() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldGiveUpAddingMessagesInTheQueueIfTheHandlerHasBeenStopped() { // given BatchingMessageHandler batchHandler = new BatchingMessageHandler(_downstreamHandler, new BoundedPriorityQueue.Config(1, 1, 1024), _batchConfig, _jobSchedulerFactory, NullLogProvider.Instance); NewEntry.Request message = new NewEntry.Request(null, new ReplicatedString("dummy")); batchHandler.Handle(Wrap(message)); // fill the queue System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); // when Thread thread = new Thread(() => { latch.Signal(); batchHandler.Handle(Wrap(message)); }); thread.Start(); latch.await(); batchHandler.Stop(); thread.Join(); // then we are not stuck and we terminate }
public void BasicUsageTest () { bool act1 = false, act2 = false; var evt = new CountdownEvent (2); var broadcast = new BroadcastBlock<int> (null); var action1 = new ActionBlock<int> (i => { act1 = i == 42; evt.Signal (); }); var action2 = new ActionBlock<int> (i => { act2 = i == 42; evt.Signal (); }); broadcast.LinkTo (action1); broadcast.LinkTo (action2); Assert.IsTrue (broadcast.Post (42)); Assert.IsTrue (evt.Wait (100)); Assert.IsTrue (act1); Assert.IsTrue (act2); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldHaveTaskQueueSizeEqualToMaxNumberOfProcessors() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldHaveTaskQueueSizeEqualToMaxNumberOfProcessors() { // GIVEN StageControl control = mock(typeof(StageControl)); //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); const int processors = 2; int maxProcessors = 5; Configuration configuration = new ConfigurationAnonymousInnerClass(this, maxProcessors); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ProcessorStep<Void> step = new BlockingProcessorStep(control, configuration, processors, latch); ProcessorStep <Void> step = new BlockingProcessorStep(control, configuration, processors, latch); step.Start(ORDER_SEND_DOWNSTREAM); step.Processors(1); // now at 2 // adding up to max processors should be fine for (int i = 0; i < processors + maxProcessors; i++) { step.Receive(i, null); } // WHEN Future <Void> receiveFuture = T2.execute(Receive(processors, step)); T2.get().waitUntilThreadState(Thread.State.TIMED_WAITING); latch.Signal(); // THEN receiveFuture.get(); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: private void runSetup(java.util.concurrent.ExecutorService executorService) throws InterruptedException private void runSetup(ExecutorService executorService) { System.Threading.CountdownEvent sync = new System.Threading.CountdownEvent(configuration.SetupTasks.Length); Console.Write("Running setup ... "); foreach (ThreadStart r in configuration.SetupTasks) { executorService.execute(wrap(r, sync)); } sync.await(); if (configuration.Color) { Console.Write(ANSI_GREEN); } Console.WriteLine("Done"); if (configuration.Color) { Console.Write(ANSI_RESET); } }
private static void Run(string[] args) { Environment.SetEnvironmentVariable("hazelcast.logging.level", "info"); Environment.SetEnvironmentVariable("hazelcast.logging.type", "console"); var config = new ClientConfig(); config.GetNetworkConfig().AddAddress("127.0.0.1"); var client = HazelcastClient.NewHazelcastClient(config); var list = client.GetList<string>("collection-listener-example"); var cdown = new CountdownEvent(3); list.AddItemListener(new ItemListener<string> { OnItemAdded = e => { Console.WriteLine("Item added: " + e.GetItem()); cdown.Signal(); }, OnItemRemoved = e => { Console.WriteLine("Item removed: " + e.GetItem()); cdown.Signal(); } }, true); list.Add("item1"); list.Add("item2"); list.Remove("item1"); cdown.Wait(); list.Destroy(); client.Shutdown(); }
// Tests that a listener is only invoked by a single thread at any time even if multiple threads are // invoking the wrapper concurrently. //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void concurrentExecution() throws InterruptedException public virtual void concurrentExecution() { int nThreads = Runtime.Runtime.availableProcessors(); int resultsPerThread = 10; ConcurrentLinkedQueue <string> errors = new ConcurrentLinkedQueue <string>(); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); int expectedResultCount = nThreads * resultsPerThread; Listener listener = new Listener(errors, latch); System.Action <CalculationResults> wrapper = new ListenerWrapper(listener, expectedResultCount, ImmutableList.of(), ImmutableList.of()); ExecutorService executor = Executors.newFixedThreadPool(nThreads); CalculationResult result = CalculationResult.of(0, 0, Result.failure(FailureReason.ERROR, "foo")); CalculationTarget target = new CalculationTargetAnonymousInnerClass(this); CalculationResults results = CalculationResults.of(target, ImmutableList.of(result)); IntStream.range(0, expectedResultCount).forEach(i => executor.submit(() => wrapper(results))); latch.await(); executor.shutdown(); if (!errors.Empty) { //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: string allErrors = errors.collect(joining("\n")); fail(allErrors); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldRunWithDelay() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldRunWithDelay() { // Given _life.start(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicLong runTime = new java.util.concurrent.atomic.AtomicLong(); AtomicLong runTime = new AtomicLong(); //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); long time = System.nanoTime(); _scheduler.schedule(Group.INDEX_POPULATION, () => { runTime.set(System.nanoTime()); latch.Signal(); }, 100, TimeUnit.MILLISECONDS); latch.await(); assertTrue(time + TimeUnit.MILLISECONDS.toNanos(100) <= runTime.get()); }
public void TestFindAllEntities() { RunAndAwait( () => { var entities = new List<FindAllEntityAsync>(); var latch = new CountdownEvent( 10 ); for( int i = 0; i < 10; i++ ) { var findAllEntity = new FindAllEntityAsync {Name = "bot_#" + i, Age = 20 + i}; Backendless.Persistence.Save( findAllEntity, new AsyncCallback<FindAllEntityAsync>( response => { entities.Add( findAllEntity ); latch.Signal(); }, fault => { for( int j = 0; j < latch.CurrentCount; j++ ) latch.Signal(); FailCountDownWith( fault ); } ) ); } latch.Wait(); Backendless.Persistence.Of<FindAllEntityAsync>() .Find( new ResponseCallback<BackendlessCollection<FindAllEntityAsync>>( this ) { ResponseHandler = backendlessCollection => AssertArgumentAndResultCollections( entities, backendlessCollection ) } ); } ); }
public void Test() { var CustomThreadPool = new CustomThreadPool(2); var Results0 = new List<int>(); var Results1 = new List<int>(); var CountdownEvent = new CountdownEvent(2); CustomThreadPool.AddTask(0, () => { Thread.Sleep(10); Results0.Add(0); }); CustomThreadPool.AddTask(0, () => { Results0.Add(1); CountdownEvent.Signal(); }); CustomThreadPool.AddTask(1, () => { Results1.Add(0); CountdownEvent.Signal(); }); CountdownEvent.Wait(); Thread.Sleep(10); Assert.IsTrue(CustomThreadPool.GetLoopIterCount(0) <= 2); Assert.IsTrue(CustomThreadPool.GetLoopIterCount(1) <= 2); Assert.AreEqual("0,1", Results0.ToStringArray()); Assert.AreEqual("0", Results1.ToStringArray()); CustomThreadPool.Stop(); }
public void Should_catch_EndOfStreamException() { // Arrange var count = new CountdownEvent(2); var channel = Substitute.For<IModel>(); var watcher = Substitute.For<IRabbitWatcher>(); var queue = Substitute.For<IInMemoryPriorityQueue<GenericPriorityMessage<BasicDeliverEventArgs>>>(); queue.When(x => x.Dequeue()).Do(callInfo => { count.Signal(); throw new EndOfStreamException(); }); var consumer = new PriorityBurrowConsumer(channel, Substitute.For<IMessageHandler>(), watcher, true, 2); var sub = Substitute.For<CompositeSubscription>(); sub.AddSubscription(new Subscription(channel) { ConsumerTag = "Burrow" }); consumer.Init(queue, sub, 1, Guid.NewGuid().ToString()); // Action consumer.Ready(); count.Wait(); // Assert consumer.Dispose(); }
public ConcurrentRunner(int maxThread, int loopEach) { this.maxThread = maxThread; this.loopEach = loopEach; this.semaphore = new SemaphoreSlim(0, maxThread); this.countdown = new CountdownEvent(maxThread); }
public void SocketConnect() { const int port = 5050; const int clientCount = 10; var listener = SocketEvents.GetTcpStreamSockets(port); var countdown = new CountdownEvent(clientCount); try { var tcs = new TaskCompletionSource<object>(); int count = 0; listener.Subscribe(s => { count++; countdown.Signal(); s.Close(); }, tcs.SetException, () => tcs.TrySetResult(null)); for (int i = 0; i < clientCount; i++) { SocketTestUtility.Connect(port); } countdown.WaitEx(); Assert.IsTrue(count == clientCount); } finally { listener.Dispose(); } }
public void Should_be_able_to_subscribe_as_exlusive() { var countdownEvent = new CountdownEvent(10); var firstCount = 0; var secondCount = 0; bus.Subscribe<MyMessage>("test", message => { countdownEvent.Signal(); Interlocked.Increment(ref firstCount); Console.WriteLine("[1] " + message.Text); }, x => x.AsExclusive()); bus.Subscribe<MyMessage>("test", message => { countdownEvent.Signal(); Interlocked.Increment(ref secondCount); Console.WriteLine("[2] " + message.Text); }, x => x.AsExclusive()); for (var i = 0; i < 10; ++i) bus.Publish(new MyMessage { Text = "Exclusive " + i }); countdownEvent.Wait(10 * 1000); Assert.IsTrue(firstCount == 10 && secondCount == 0 || firstCount == 0 && secondCount == 10); Console.WriteLine("Stopped consuming"); }
static void Main(string[] args) { // initialize the semaphores semA = new SemaphoreSlim(2); semB = new SemaphoreSlim(2); // define the number of tasks we will use int taskCount = 10; // initialize the barrier cdEvent = new CountdownEvent(taskCount); Task[] tasks = new Task[10]; for (int i = 0; i < taskCount; i++) { tasks[i] = Task.Factory.StartNew((stateObject) => { InitialMethod((int)stateObject); Console.WriteLine("Task {0} completed", Task.CurrentId); }, i); } // wait for all of the tasks to have reached a terminal method cdEvent.Wait(); // throw an exception to force the debugger to break throw new Exception(); }
public void Should_load_share_between_multiple_consumers() { var countdownEvent = new CountdownEvent(2); MyMessage receivedMessage1 = null; bus.Subscribe<MyMessage>("subscriberId", message => { Console.WriteLine("Handler A got '{0}'", message.Text); receivedMessage1 = message; countdownEvent.Signal(); }); MyMessage receivedMessage2 = null; bus.Subscribe<MyMessage>("subscriberId", message => { Console.WriteLine("Handler B got '{0}'", message.Text); receivedMessage2 = message; countdownEvent.Signal(); }); var publishedMessage1 = new MyMessage { Text = "Hello There From The First!" }; var publishedMessage2 = new MyMessage { Text = "Hello There From The Second!" }; using (var channel = bus.OpenPublishChannel()) { channel.Publish(publishedMessage1); channel.Publish(publishedMessage2); } // give the task background thread time to process the message. countdownEvent.Wait(); receivedMessage1.Text.ShouldEqual(publishedMessage1.Text); receivedMessage2.Text.ShouldEqual(publishedMessage2.Text); }
protected override long RunDisruptorPass() { CountdownEvent latch = new CountdownEvent(1); long expectedCount = batchEventProcessor.Sequence.Value + ITERATIONS; handler.Reset(latch, ITERATIONS); Task.Factory.StartNew(() => batchEventProcessor.Run()); Stopwatch start = Stopwatch.StartNew(); RingBuffer<long[]> rb = ringBuffer; for (long i = 0; i < ITERATIONS; i++) { long next = rb.Next(); long[] @event = rb.Get(next); for (int j = 0; j < @event.Length; j++) { @event[j] = i; } rb.Publish(next); } latch.Wait(); long opsPerSecond = (ITERATIONS * ARRAY_SIZE * 1000L) / (start.ElapsedMilliseconds); waitForEventProcessorSequence(expectedCount); batchEventProcessor.Halt(); PerfTestUtil.failIf(0, handler.Value); return opsPerSecond; }
public void ProperRooting_NoGC_SingleShot() { var cts = new CancellationTokenSource(); new Thread(() => { while (!cts.IsCancellationRequested) { Thread.Sleep(50); GC.Collect(); GC.WaitForPendingFinalizers(); } }).Start(); var tp = ThreadPoolScheduler.Instance; var N = 100; var cd = new CountdownEvent(N); for (int i = 0; i < N; i++) { tp.Schedule(TimeSpan.FromMilliseconds(100 + i), () => { cd.Signal(); }); } Assert.True(cd.Wait(TimeSpan.FromMinutes(1))); cts.Cancel(); }
public void HydratingFromMultipleThreads_IsSafe() { var numberOfHydrations = 0; var cache = new CachedValue<int>(() => ++numberOfHydrations); Assert.That(cache.Value, Is.EqualTo(1)); using (var countdownEvent = new CountdownEvent(2)) { Action threadAction = () => { cache.Invalidate(); countdownEvent.Signal(); countdownEvent.Wait(); Assert.That(cache.Value, Is.EqualTo(2)); }; var t1 = threadAction.BeginInvoke(threadAction.EndInvoke, null); var t2 = threadAction.BeginInvoke(threadAction.EndInvoke, null); WaitHandle.WaitAll(new[]{t1.AsyncWaitHandle, t2.AsyncWaitHandle}); } Assert.That(numberOfHydrations, Is.EqualTo(2)); }
public IDisposable Start() { _monitor.Start(); CountdownEvent pending = new CountdownEvent(_args.ConnectionLimit); var interval = Observable.Interval(TimeSpan.FromSeconds(1)) .TakeWhile(_ => pending.CurrentCount > 0) .Subscribe(async _ => { var parallelCount = Math.Min(pending.CurrentCount, 10); Task[] tasks = new Task[parallelCount]; for (int i = 0; i < parallelCount; i++) { tasks[i] = Task.Run(() => Connect(pending)); } Task.WaitAll(tasks); }, ex => { Console.WriteLine(ex.Message); Environment.Exit(1); }); pending.Wait(); Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(this.SendMessage); return null; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void terminatedTransactionDoesNotForceUpdatePulling() public virtual void TerminatedTransactionDoesNotForceUpdatePulling() { int testTxsOnMaster = 42; ClusterManager.ManagedCluster cluster = ClusterRule.withSharedSetting(HaSettings.pull_interval, "0s").withSharedSetting(HaSettings.tx_push_factor, "0").startCluster(); HighlyAvailableGraphDatabase master = cluster.Master; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final org.neo4j.kernel.ha.HighlyAvailableGraphDatabase slave = cluster.getAnySlave(); HighlyAvailableGraphDatabase slave = cluster.AnySlave; CreateNodeOn(master); cluster.Sync(); long lastClosedTxIdOnMaster = LastClosedTxIdOn(master); long lastClosedTxIdOnSlave = LastClosedTxIdOn(slave); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch slaveTxStarted = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent slaveTxStarted = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch slaveShouldCommit = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent slaveShouldCommit = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.atomic.AtomicReference<org.neo4j.graphdb.Transaction> slaveTx = new java.util.concurrent.atomic.AtomicReference<>(); AtomicReference <Transaction> slaveTx = new AtomicReference <Transaction>(); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.concurrent.Future<?> slaveCommit = java.util.concurrent.Executors.newSingleThreadExecutor().submit(() -> Future <object> slaveCommit = Executors.newSingleThreadExecutor().submit(() => { using (Transaction tx = slave.BeginTx()) { slaveTx.set(tx); slaveTxStarted.Signal(); Await(slaveShouldCommit); tx.success(); } }); Await(slaveTxStarted); CreateNodesOn(master, testTxsOnMaster); assertNotNull(slaveTx.get()); slaveTx.get().terminate(); slaveShouldCommit.Signal(); try { slaveCommit.get(); fail("Exception expected"); } catch (Exception e) { assertThat(e, instanceOf(typeof(ExecutionException))); assertThat(e.InnerException, instanceOf(typeof(TransientTransactionFailureException))); } assertEquals(lastClosedTxIdOnMaster + testTxsOnMaster, LastClosedTxIdOn(master)); assertEquals(lastClosedTxIdOnSlave, LastClosedTxIdOn(slave)); }
private Worker NewWorker(GraphDatabaseService db, System.Threading.CountdownEvent startSignal, AtomicBoolean stopSignal, AtomicReference <Exception> failure, Node parentNode) { Worker worker = new Worker(db, startSignal, stopSignal, failure, parentNode); worker.Start(); return(worker); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void awaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: internal virtual void AwaitingShutdownMustBlockUntilAllMessagesHaveBeenProcessed() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Event specialShutdownObservedEvent = new Event(); Event specialShutdownObservedEvent = new Event(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch awaitStartLatch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent awaitStartLatch = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final EventConsumer consumer = new EventConsumer(); EventConsumer consumer = new EventConsumer(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final AsyncEvents<Event> asyncEvents = new AsyncEvents<>(consumer, AsyncEvents.Monitor_Fields.NONE); AsyncEvents <Event> asyncEvents = new AsyncEvents <Event>(consumer, AsyncEvents.Monitor_Fields.None); _executor.submit(asyncEvents); // Wait for the background thread to start processing events do { asyncEvents.Send(new Event()); } while (consumer.EventsProcessed.take().processedBy == Thread.CurrentThread); // Start a thread that awaits the termination //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.concurrent.Future<?> awaitShutdownFuture = executor.submit(() -> Future <object> awaitShutdownFuture = _executor.submit(() => { awaitStartLatch.Signal(); asyncEvents.AwaitTermination(); consumer.EventsProcessed.offer(specialShutdownObservedEvent); }); awaitStartLatch.await(); // Send 5 events asyncEvents.Send(new Event()); asyncEvents.Send(new Event()); asyncEvents.Send(new Event()); asyncEvents.Send(new Event()); asyncEvents.Send(new Event()); // Observe 5 events processed assertThat(consumer.EventsProcessed.take(), @is(notNullValue())); assertThat(consumer.EventsProcessed.take(), @is(notNullValue())); assertThat(consumer.EventsProcessed.take(), @is(notNullValue())); assertThat(consumer.EventsProcessed.take(), @is(notNullValue())); assertThat(consumer.EventsProcessed.take(), @is(notNullValue())); // Observe no events left assertThat(consumer.EventsProcessed.poll(20, TimeUnit.MILLISECONDS), @is(nullValue())); // Shutdown and await termination asyncEvents.Shutdown(); awaitShutdownFuture.get(); // Observe termination assertThat(consumer.EventsProcessed.take(), sameInstance(specialShutdownObservedEvent)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void shouldNotifyListenerWhenNewLogIsCreated() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: internal virtual void ShouldNotifyListenerWhenNewLogIsCreated() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch allowRotationComplete = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent allowRotationComplete = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch rotationComplete = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent rotationComplete = new System.Threading.CountdownEvent(1); string outputFileCreatedMessage = "Output file created"; string rotationCompleteMessage = "Rotation complete"; RotationListener rotationListener = spy(new RotationListenerAnonymousInnerClass(this, allowRotationComplete, rotationComplete, outputFileCreatedMessage, rotationCompleteMessage)); ExecutorService rotationExecutor = Executors.newSingleThreadExecutor(); try { RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier(_fileSystem, _logFile, 10, 0, 10, rotationExecutor, rotationListener); Write(supplier, "A string longer than 10 bytes"); Write(supplier, "A string longer than 10 bytes"); allowRotationComplete.Signal(); rotationComplete.await(1L, TimeUnit.SECONDS); verify(rotationListener).outputFileCreated(any(typeof(Stream))); verify(rotationListener).rotationCompleted(any(typeof(Stream))); } finally { ShutDownExecutor(rotationExecutor); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void rotationShouldNotDeadlockOnListener() internal virtual void RotationShouldNotDeadlockOnListener() { assertTimeout(ofMillis(TEST_TIMEOUT_MILLIS), () => { string logContent = "Output file created"; AtomicReference <Exception> listenerException = new AtomicReference <Exception>(null); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); RotationListener listener = new RotationListenerAnonymousInnerClass(this, listenerException, latch); ExecutorService executor = Executors.newSingleThreadExecutor(); DefaultFileSystemAbstraction defaultFileSystemAbstraction = new DefaultFileSystemAbstraction(); RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier(defaultFileSystemAbstraction, _logFile, 0, 0, 10, executor, listener); Stream outputStream = supplier.Get(); LockingPrintWriter lockingPrintWriter = new LockingPrintWriter(this, outputStream); lockingPrintWriter.WithLock(() => { supplier.Rotate(); latch.await(); return(Void.TYPE); }); ShutDownExecutor(executor); IList <string> strings = Files.readAllLines(_logFile.toPath()); string actual = string.join("", strings); assertEquals(logContent, actual); assertNull(listenerException.get()); }); }
public MainWindow() { InitializeComponent(); Thread.CurrentThread.Name = "Main Thread"; CountdownEvent folderEndByXML = new CountdownEvent(1); CountdownEvent folderEndByTree = new CountdownEvent(1); CountdownEvent fileEndByXML = new CountdownEvent(1); CountdownEvent fileEndByTree = new CountdownEvent(1); m_parser = new Parser(m_progressToken, folderEndByTree, folderEndByXML, fileEndByTree, fileEndByXML); m_treeFiller = new TreeFiller(m_treeView, m_progressToken, folderEndByTree, fileEndByTree); m_xmlFiller = new XMLFiller(m_progressToken, folderEndByXML, fileEndByXML); m_folderName.DataContext = m_parser; m_xmlFileName.DataContext = m_xmlFiller; m_parser.ItemGrabbed += m_xmlFiller.ItemGrabbedHandler; m_parser.ItemGrabbed += m_treeFiller.ItemGrabbedHandler; m_parser.FolderStarted += m_xmlFiller.FolderStartedHandler; m_parser.FolderStarted += m_treeFiller.FolderStartedHandler; m_parser.FolderFinished += m_xmlFiller.FolderFinishedHandler; m_parser.FolderFinished += m_treeFiller.FolderFinishedHandler; m_parser.ParserFinishEvent += this.ParserFinishEventHandler; m_xmlFiller.ExceptionOccuredEvent += this.ExceptionOccuredHandler; m_treeFiller.ExceptionOccuredEvent += this.ExceptionOccuredHandler; m_parser.ExceptionOccuredEvent += this.ExceptionOccuredHandler; }
protected List<PerformanceRecord> ExecuteWriteWithParallel(IEnumerable<TestData> data, int numberOfTransactions, int itemsPerTransaction, int numberOfThreads, Func<IEnumerator<TestData>, long, long, List<PerformanceRecord>> writeFunction, out long elapsedMilliseconds) { var countdownEvent = new CountdownEvent(numberOfThreads); var parallelData = SplitData(data, numberOfTransactions, itemsPerTransaction, numberOfThreads); var records = new List<PerformanceRecord>[numberOfThreads]; var sw = Stopwatch.StartNew(); for (int i = 0; i < numberOfThreads; i++) { ThreadPool.QueueUserWorkItem( state => { var index = (int)state; var pData = parallelData[index]; records[index] = writeFunction(pData.Enumerate(), pData.ItemsPerTransaction, pData.NumberOfTransactions); countdownEvent.Signal(); }, i); } countdownEvent.Wait(); sw.Stop(); elapsedMilliseconds = sw.ElapsedMilliseconds; return records .SelectMany(x => x) .ToList(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void shouldNotUpdateOutputStreamWhenClosedDuringRotation() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: internal virtual void ShouldNotUpdateOutputStreamWhenClosedDuringRotation() { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch allowRotationComplete = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent allowRotationComplete = new System.Threading.CountdownEvent(1); RotationListener rotationListener = spy(new RotationListenerAnonymousInnerClass2(this, allowRotationComplete)); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.List<java.io.OutputStream> mockStreams = new java.util.ArrayList<>(); IList <Stream> mockStreams = new List <Stream>(); FileSystemAbstraction fs = new DelegatingFileSystemAbstractionAnonymousInnerClass(this, _fileSystem, mockStreams); ExecutorService rotationExecutor = Executors.newSingleThreadExecutor(); try { RotatingFileOutputStreamSupplier supplier = new RotatingFileOutputStreamSupplier(fs, _logFile, 10, 0, 10, rotationExecutor, rotationListener); Stream outputStream = supplier.Get(); Write(supplier, "A string longer than 10 bytes"); assertThat(supplier.Get(), @is(outputStream)); allowRotationComplete.Signal(); supplier.Dispose(); } finally { ShutDownExecutor(rotationExecutor); } AssertStreamClosed(mockStreams[0]); }
public void Constructor_Zero () { var ce = new CountdownEvent (0); Assert.IsTrue (ce.IsSet, "#1"); Assert.AreEqual (0, ce.InitialCount, "#2"); Assert.IsTrue (ce.Wait (0), "#3"); }
public void Should_execute_less_than_4_seconds() { ThreadPool.SetMinThreads(NumThreads, NumThreads); Console.WriteLine("Burst test started"); _mre.Reset(); _countdown = new CountdownEvent(NumThreads); for (var i = 0; i < NumThreads; i++) { new Thread(OneThreadExecution) { Name = "Thread " + i }.Start(); } _countdown.Wait(); var dateTime = DateTime.Now; _countdown = new CountdownEvent(NumThreads); _mre.Set(); _countdown.Wait(); var timeSpan = DateTime.Now - dateTime; Console.WriteLine("Test finished"); Console.WriteLine("Executed at {0}.{1:0}s.", timeSpan.Seconds, timeSpan.Milliseconds / 100); if (timeSpan.Seconds > 5) { Assert.Ignore("This test should't take more than to 4 seconds to run"); } }
public void should_reconnect_within_5_seconds() { const int total = 100; var countdown = new CountdownEvent(total); IBus producer = this.StartBus("producer", cfg => cfg.Route("boo")); IBus consumer = this.StartBus( "consumer", cfg => cfg.On<BooMessage>("boo"). ReactWith( (m, ctx) => { Console.WriteLine("Received {0}.", m.Num); countdown.Signal(); })); int count = total; while (count -- > 0) { producer.Emit("boo", new BooMessage(count)); Console.WriteLine("Sent {0}.", count); Thread.Sleep(1.Seconds()); } countdown.Wait(); }
public static void AwaitLatch(System.Threading.CountdownEvent latch, bool uninterruptedWaiting) { long now = DateTimeHelper.CurrentUnixTimeMillis(); long deadline = DateTimeHelper.CurrentUnixTimeMillis() + _fiveMinutes; while (now < deadline) { try { long waitingTime = Math.Min(Math.Max(0, deadline - now), 5000L); if (latch.await(waitingTime, TimeUnit.MILLISECONDS)) { return; } else { Thread.yield(); } } catch (InterruptedException e) { Thread.interrupted(); if (!uninterruptedWaiting) { throw new Exception("Thread interrupted while waiting on latch", e); } } now = DateTimeHelper.CurrentUnixTimeMillis(); } throw new AssertionError("Latch specified waiting time elapsed."); }
//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))); }
internal Worker(GraphDatabaseService db, System.Threading.CountdownEvent startSignal, AtomicBoolean stopSignal, AtomicReference <Exception> failure, Node parentNode) { this.Db = db; this.StartSignal = startSignal; this.StopSignal = stopSignal; this.Failure = failure; this.ParentNode = parentNode; }
internal Populator(DynamicIndexStoreViewIT outerInstance, GraphDatabaseService databaseService, long totalNodes, System.Threading.CountdownEvent startSignal, AtomicBoolean endSignal) { this._outerInstance = outerInstance; this.DatabaseService = databaseService; this.TotalNodes = totalNodes; this.StartSignal = startSignal; this.EndSignal = endSignal; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void terminateNestedTransactionThrowsExceptionOnNextNestedOperationMultiThreadedVersionWithNestedTx() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void TerminateNestedTransactionThrowsExceptionOnNextNestedOperationMultiThreadedVersionWithNestedTx() { // Given //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final GraphDatabaseService db = getTemporaryDatabase(); GraphDatabaseService db = TemporaryDatabase; try { // When //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch txSet = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent txSet = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch terminated = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent terminated = new System.Threading.CountdownEvent(1); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Transaction[] outer = {null}; Transaction[] outer = new Transaction[] { null }; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Exception[] threadFail = {null}; Exception[] threadFail = new Exception[] { null }; Thread worker = new Thread(() => { Transaction transaction = Db.beginTx(); try { using (Transaction inner = Db.beginTx()) { outer[0] = inner; txSet.Signal(); terminated.await(); Db.createNode(); fail("should have failed earlier"); } } catch (Exception e) { threadFail[0] = e; } finally { transaction.Close(); } }); worker.Start(); txSet.await(); outer[0].Terminate(); terminated.Signal(); worker.Join(); assertThat(threadFail[0], instanceOf(typeof(TransactionTerminatedException))); } finally { Db.shutdown(); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test void concurrentlyPublishedEventsMustAllBeProcessed() internal virtual void ConcurrentlyPublishedEventsMustAllBeProcessed() { assertTimeout(ofSeconds(10), () => { EventConsumer consumer = new EventConsumer(); System.Threading.CountdownEvent startLatch = new System.Threading.CountdownEvent(1); const int threads = 10; const int iterations = 2_000; AsyncEvents <Event> asyncEvents = new AsyncEvents <Event>(consumer, AsyncEvents.Monitor_Fields.None); _executor.submit(asyncEvents); ExecutorService threadPool = Executors.newFixedThreadPool(threads); ThreadStart runner = () => { try { startLatch.await(); } catch (InterruptedException e) { throw new Exception(e); } for (int i = 0; i < iterations; i++) { asyncEvents.Send(new Event()); } }; for (int i = 0; i < threads; i++) { threadPool.submit(runner); } startLatch.countDown(); Thread thisThread = Thread.CurrentThread; int eventCount = threads * iterations; try { for (int i = 0; i < eventCount; i++) { Event @event = consumer.Poll(1, TimeUnit.SECONDS); if (@event == null) { i--; } else { assertThat(@event.ProcessedBy, @is(not(thisThread))); } } } finally { asyncEvents.Shutdown(); threadPool.shutdown(); } }); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ForceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() { // Given Lock @lock = new ReentrantLock(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.locks.Lock spyLock = spy(lock); Lock spyLock = spy(@lock); doAnswer(invocation => { verify(_appender).checkPoint(any(typeof(LogPosition)), any(typeof(LogCheckPointEvent))); reset(_appender); invocation.callRealMethod(); return(null); }).when(spyLock).unlock(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final CheckPointerImpl checkPointing = checkPointer(mutex(spyLock)); CheckPointerImpl checkPointing = CheckPointer(Mutex(spyLock)); MockTxIdStore(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch startSignal = new java.util.concurrent.CountDownLatch(2); System.Threading.CountdownEvent startSignal = new System.Threading.CountdownEvent(2); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch completed = new java.util.concurrent.CountDownLatch(2); System.Threading.CountdownEvent completed = new System.Threading.CountdownEvent(2); checkPointing.Start(); Thread checkPointerThread = new CheckPointerThread(checkPointing, startSignal, completed); Thread forceCheckPointThread = new Thread(() => { try { startSignal.Signal(); startSignal.await(); checkPointing.ForceCheckPoint(_info); completed.Signal(); } catch (Exception e) { throw new Exception(e); } }); // when checkPointerThread.Start(); forceCheckPointThread.Start(); completed.await(); verify(spyLock, times(2)).@lock(); verify(spyLock, times(2)).unlock(); }
//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 createWriter(final RWLock lock, final LockTransaction transaction, final java.util.concurrent.CountDownLatch latch) private ThreadStart CreateWriter(RWLock @lock, LockTransaction transaction, System.Threading.CountdownEvent latch) { return(() => { @lock.Mark(); @lock.AcquireWriteLock(LockTracer.NONE, transaction); latch.Signal(); }); }
public RunnableAnonymousInnerClass(HighestIdTest outerInstance, [email protected] highestId, System.Threading.CountdownEvent latch, AtomicLongArray highestIds, int cc) { this.outerInstance = outerInstance; this._highestId = highestId; this._latch = latch; this._highestIds = highestIds; this._cc = cc; random = ThreadLocalRandom.current(); }
internal Committer(IdOrderingQueue queue, LongIterator idSource, AtomicBoolean end, System.Threading.CountdownEvent readySignal, System.Threading.CountdownEvent startSignal) { this.Queue = queue; this.IdSource = idSource; this.End = end; this.ReadySignal = readySignal; this.StartSignal = startSignal; start(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testLockCounters() throws InterruptedException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void TestLockCounters() { RagManager ragManager = new RagManager(); LockResource resource = new LockResource(ResourceTypes.NODE, 1L); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final RWLock lock = createRWLock(ragManager, resource); RWLock @lock = CreateRWLock(ragManager, resource); LockTransaction lockTransaction = new LockTransaction(); LockTransaction anotherTransaction = new LockTransaction(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final LockTransaction writeTransaction = new LockTransaction(); LockTransaction writeTransaction = new LockTransaction(); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final java.util.concurrent.CountDownLatch writerCompletedLatch = new java.util.concurrent.CountDownLatch(1); System.Threading.CountdownEvent writerCompletedLatch = new System.Threading.CountdownEvent(1); @lock.Mark(); @lock.AcquireReadLock(LockTracer.NONE, lockTransaction); @lock.Mark(); @lock.AcquireReadLock(LockTracer.NONE, anotherTransaction); assertEquals(2, @lock.ReadCount); assertEquals(0, @lock.WriteCount); assertEquals(2, @lock.TxLockElementCount); ThreadStart writer = CreateWriter(@lock, writeTransaction, writerCompletedLatch); _executor.submit(writer); WaitWaitingThreads(@lock, 1); // check that all reader, writes, threads counters are correct assertEquals(2, @lock.ReadCount); assertEquals(0, @lock.WriteCount); assertEquals(3, @lock.TxLockElementCount); assertEquals(1, @lock.WaitingThreadsCount); @lock.ReleaseReadLock(lockTransaction); @lock.ReleaseReadLock(anotherTransaction); writerCompletedLatch.await(); // test readers and waiting thread gone assertEquals(0, @lock.ReadCount); assertEquals(1, @lock.WriteCount); assertEquals(1, @lock.TxLockElementCount); assertEquals(0, @lock.WaitingThreadsCount); @lock.ReleaseWriteLock(writeTransaction); // check lock is clean in the end assertEquals(0, @lock.TxLockElementCount); assertEquals(0, @lock.WaitingThreadsCount); assertEquals(0, @lock.ReadCount); assertEquals(0, @lock.WriteCount); }
/// <summary> /// Set a trap for the eviction thread, and return a CountDownLatch with a counter set to 1. /// When the eviction thread performs the given trap-event, it will block on the latch after /// making the event observable. /// </summary> public virtual System.Threading.CountdownEvent Trap <T1>(Matcher <T1> trap) where T1 : Event { lock (this) { Debug.Assert(trap != null); _trapLatch = new System.Threading.CountdownEvent(1); this._trap = trap; return(_trapLatch); } }
private ICollection <Worker> CreateWorkers(GraphDatabaseService db, System.Threading.CountdownEvent startSignal, AtomicBoolean stopSignal, AtomicReference <Exception> failure, Node parentNode) { ICollection <Worker> workers = new List <Worker>(); for (int i = 0; i < 2; i++) { workers.Add(NewWorker(db, startSignal, stopSignal, failure, parentNode)); } return(workers); }
internal RunnableReader(GBPTreeConcurrencyITBase <KEY, VALUE> outerInstance, TestCoordinator testCoordinator, System.Threading.CountdownEvent readerReadySignal, System.Threading.CountdownEvent readerStartSignal, AtomicBoolean endSignal, AtomicBoolean failHalt, AtomicReference <Exception> readerError) { this._outerInstance = outerInstance; this.ReaderReadySignal = readerReadySignal; this.ReaderStartSignal = readerStartSignal; this.EndSignal = endSignal; this.FailHalt = failHalt; this.ReaderError = readerError; this.TestCoordinator = testCoordinator; }
public StressRunBase(RunData runData) { RunData = runData; Resolver = new DefaultDependencyResolver(); CancellationTokenSource = new CancellationTokenSource(); _countDown = new CountdownEvent(runData.Senders); }