Exemplo n.º 1
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void readAndWrite(int nReaders, int time, java.util.concurrent.TimeUnit unit) throws Throwable
        private void ReadAndWrite(int nReaders, int time, TimeUnit unit)
        {
            using (DefaultFileSystemAbstraction fsa = new DefaultFileSystemAbstraction())
            {
                LifeSupport lifeSupport = new LifeSupport();
                T           raftLog     = CreateRaftLog(fsa, Dir.directory());
                lifeSupport.Add(raftLog);
                lifeSupport.Start();

                try
                {
                    ExecutorService es = Executors.newCachedThreadPool();

                    ICollection <Future <long> > futures = new List <Future <long> >();
                    futures.Add(es.submit(new TimedTask(this, () => write(raftLog), time, unit)));

                    for (int i = 0; i < nReaders; i++)
                    {
                        futures.Add(es.submit(new TimedTask(this, () => read(raftLog), time, unit)));
                    }

                    foreach (Future <long> f in futures)
                    {
                        long iterations = f.get();
                    }

                    es.shutdown();
                }
                finally
                {
                    lifeSupport.Shutdown();
                }
            }
        }
Exemplo n.º 2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldHandleStress() throws java.util.concurrent.ExecutionException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void ShouldHandleStress()
        {
            // given
            int n = 1000;
            TestStateMachine stateMachine = new TestStateMachine();
            ExecutorService  executor     = Executors.newFixedThreadPool(3);

            // when
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> collect = executor.submit(stress(n, () -> collect(stateMachine)));
            Future <object> collect = executor.submit(Stress(n, () => collect(stateMachine)));
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> stop = executor.submit(stress(n, () -> stateMachine.stop(Long.MAX_VALUE)));
            Future <object> stop = executor.submit(Stress(n, () => stateMachine.Stop(long.MaxValue)));
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> clear = executor.submit(stress(n, stateMachine::clear));
            Future <object> clear = executor.submit(Stress(n, stateMachine.clear));
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> status = executor.submit(stress(n, stateMachine::status));
            Future <object> status = executor.submit(Stress(n, stateMachine.status));

            // then without illegal transitions or exceptions
            collect.get();
            stop.get();
            clear.get();
            status.get();
            executor.shutdown();
        }
        public virtual void ShouldBeAbleToReadPropertiesFromNewNodeReturnedFromIndex()
        {
            string        propertyKey   = System.Guid.randomUUID().ToString();
            string        propertyValue = System.Guid.randomUUID().ToString();
            AtomicBoolean start         = new AtomicBoolean(false);
            int           readerDelay   = ThreadLocalRandom.current().Next(MAX_READER_DELAY_MS);

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

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

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

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

            assertNull(writeResult.get());
            assertNull(readResult.get());
        }
Exemplo n.º 4
0
//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);
        }
Exemplo n.º 5
0
        internal override ExecutorService SetupWorkload(int n)
        {
            ExecutorService service = Executors.newFixedThreadPool(2 * n);

            for (int i = 0; i < n; i++)
            {
                service.submit(new IrrationalUserAdmin(this, i));
                service.submit(new IrrationalRoleAdmin(this, i));
            }
            return(service);
        }
Exemplo n.º 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRun() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRun()
        {
            ExecutorService service = Executors.newFixedThreadPool(3);

            service.submit(_createUserWork);
            service.submit(_deleteUserWork);
            service.submit(_transactionWork);

            service.awaitTermination(30, TimeUnit.SECONDS);

            string msg = string.join(Environment.NewLine, _errors.Select(Exception.getMessage).ToList());

            assertThat(msg, _errors, empty());
        }
Exemplo n.º 7
0
        // 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);
            }
        }
Exemplo n.º 8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void unusedEntriesSafelyAcquiredOnCleanup() throws ConcurrentAccessException, NoSuchEntryException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void UnusedEntriesSafelyAcquiredOnCleanup()
        {
            CountDownReaper countDownReaper = new CountDownReaper();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final TimedRepository<Object,long> timedRepository = new TimedRepository<>(provider, countDownReaper, 1, clock);
            TimedRepository <object, long> timedRepository = new TimedRepository <object, long>(_provider, countDownReaper, 1, _clock);
            ExecutorService     singleThreadExecutor       = Executors.newSingleThreadExecutor();
            NonStoppableCleaner cleaner = new NonStoppableCleaner(timedRepository);

            try
            {
                singleThreadExecutor.submit(cleaner);

                long entryKey   = 1L;
                long iterations = 100000L;
                while (entryKey++ < iterations)
                {
                    timedRepository.Begin(entryKey);
                    timedRepository.Acquire(entryKey);
                    _clock.forward(10, TimeUnit.MILLISECONDS);
                    timedRepository.Release(entryKey);
                    timedRepository.End(entryKey);

                    countDownReaper.Await("Reaper should consume entry from cleaner thread or from our 'end' call. " + "If it was not consumed it mean cleaner and worker thread where not able to" + " figure out who removes entry, and block will ends up in the repo forever.", 10, SECONDS);
                    countDownReaper.Reset();
                }
            }
            finally
            {
                cleaner.Stop();
                singleThreadExecutor.shutdownNow();
            }
        }
Exemplo n.º 9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void checkClientsIdBounds() throws java.util.concurrent.ExecutionException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void CheckClientsIdBounds()
        {
            int                threads     = 2;
            DefaultCounts      counts      = new DefaultCounts(threads);
            DefaultCacheAccess cacheAccess = new DefaultCacheAccess(counts, threads);

            cacheAccess.PrepareForProcessingOfSingleStore(34);

            CacheAccess_Client client1 = cacheAccess.Client();

            assertTrue(client1.WithinBounds(0));
            assertTrue(client1.WithinBounds(10));
            assertTrue(client1.WithinBounds(33));
            assertFalse(client1.WithinBounds(34));

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> secondClientIdChecks = executor.submit(() ->
            Future <object> secondClientIdChecks = _executor.submit(() =>
            {
                CacheAccess_Client client = cacheAccess.Client();
                assertFalse(client.WithinBounds(5));
                assertFalse(client.WithinBounds(33));
                assertTrue(client.WithinBounds(34));
                assertTrue(client.WithinBounds(67));
                assertFalse(client.WithinBounds(68));
            });

            secondClientIdChecks.get();
        }
Exemplo n.º 10
0
 public override void Start()
 {
     _highCount = 0;
     _executor  = Executors.newSingleThreadExecutor(new NamedThreadFactory(this.GetType().Name));
     _executor.submit(_events);
     _events.awaitStartup();
 }
Exemplo n.º 11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void mergeScanUpdates() throws InterruptedException, java.util.concurrent.ExecutionException, java.io.IOException
        private void MergeScanUpdates()
        {
            ExecutorService executorService = Executors.newFixedThreadPool(_allScanUpdates.Count);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<java.util.concurrent.Future<?>> mergeFutures = new java.util.ArrayList<>();
            IList <Future <object> > mergeFutures = new List <Future <object> >();

            foreach (ThreadLocalBlockStorage part in _allScanUpdates)
            {
                BlockStorage <KEY, VALUE> scanUpdates = part.BlockStorage;
                // Call doneAdding here so that the buffer it allocates if it needs to flush something will be shared with other indexes
                scanUpdates.DoneAdding();
                mergeFutures.Add(executorService.submit(() =>
                {
                    scanUpdates.Merge(_mergeFactor, _cancellation);
                    return(null);
                }));
            }
            executorService.shutdown();
            while (!executorService.awaitTermination(1, TimeUnit.SECONDS))
            {
                // just wait longer
            }
            // Let potential exceptions in the merge threads have a chance to propagate
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.concurrent.Future<?> mergeFuture : mergeFutures)
            foreach (Future <object> mergeFuture in mergeFutures)
            {
                mergeFuture.get();
            }
        }
Exemplo n.º 12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("Duplicates") @Test public void stressCache() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void StressCache()
        {
            StringFactory factory             = new StringFactory();
            TemporalIndexCache <string> cache = new TemporalIndexCache <string>(factory);

            ExecutorService pool = Executors.newFixedThreadPool(20);

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

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

                Thread.Sleep(5_000);

                shouldContinue.set(false);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.concurrent.Future<?> future : futures)
                foreach (Future <object> future in futures)
                {
                    future.get(10, TimeUnit.SECONDS);
                }
            }
            finally
            {
                pool.shutdown();
            }
        }
Exemplo n.º 13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldInvokeHandlerOnQueuedMessage() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldInvokeHandlerOnQueuedMessage()
        {
            // given
            BatchingMessageHandler batchHandler = new BatchingMessageHandler(_downstreamHandler, _inQueueConfig, _batchConfig, _jobSchedulerFactory, NullLogProvider.Instance);
            ReplicatedString       content      = new ReplicatedString("dummy");

            NewEntry.Request message = new NewEntry.Request(null, content);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> future = executor.submit(batchHandler);
            Future <object> future = _executor.submit(batchHandler);

            // Some time for letting the batch handler block on its internal queue.
            //
            // It is fine if it sometimes doesn't get that far in time, just that we
            // usually want to test the wake up from blocking state.
            Thread.Sleep(50);

            // when
            batchHandler.Handle(Wrap(message));

            // then
            future.get();
            NewEntry.BatchRequest expected = new NewEntry.BatchRequest(singletonList(content));
            verify(_downstreamHandler).handle(Wrap(expected));
        }
Exemplo n.º 14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldSupportConcurrentConsumptionOfSlaves() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldSupportConcurrentConsumptionOfSlaves()
        {
            // Given
            LogEntryReader <ReadableClosablePositionAwareChannel> logEntryReader = new VersionAwareLogEntryReader <ReadableClosablePositionAwareChannel>();
            HighAvailabilitySlaves haSlaves = new HighAvailabilitySlaves(ClusterMembersOfSize(1000), mock(typeof(Cluster)), new DefaultSlaveFactory(NullLogProvider.Instance, new Monitors(), 42, Suppliers.singleton(logEntryReader)), new HostnamePort(null, 0));

            // When
            ExecutorService executor = Executors.newFixedThreadPool(5);

            for (int i = 0; i < 5; i++)
            {
                executor.submit(SlavesConsumingRunnable(haSlaves));
            }
            executor.shutdown();
            executor.awaitTermination(30, SECONDS);

            // Then
            int         slavesCount = 0;
            LifeSupport life        = ReflectionUtil.getPrivateField(haSlaves, "life", typeof(LifeSupport));

            foreach (Lifecycle lifecycle in life.LifecycleInstances)
            {
                if (lifecycle is Slave)
                {
                    slavesCount++;
                }
            }
            assertEquals("Unexpected number of slaves", 1000 - 1, slavesCount);                 // One instance is master
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void someData() throws InterruptedException
        private void SomeData()
        {
            int             threads  = Runtime.Runtime.availableProcessors();
            ExecutorService executor = Executors.newFixedThreadPool(threads);

            for (int i = 0; i < threads; i++)
            {
                executor.submit(() =>
                {
                    for (int t = 0; t < 100; t++)
                    {
                        using (Transaction tx = Db.beginTx())
                        {
                            for (int n = 0; n < 100; n++)
                            {
                                Node node = Db.createNode(_labels);
                                foreach (string key in _keys)
                                {
                                    node.setProperty(key, format("some value %d", n));
                                }
                            }
                            tx.success();
                        }
                    }
                });
            }
            executor.shutdown();
            while (!executor.awaitTermination(1, SECONDS))
            {
                // Just wait longer
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void createdExecutorShouldFavorPoolSizes()
        public virtual void CreatedExecutorShouldFavorPoolSizes()
        {
            AtomicBoolean exitCondition = new AtomicBoolean(false);
            AtomicInteger threadCounter = new AtomicInteger(0);

            _executorService = _factory.create(0, 5, Duration.ZERO, 0, false, NewThreadFactoryWithCounter(threadCounter));

            assertNotNull(_executorService);
            assertEquals(0, threadCounter.get());

            try
            {
                for (int i = 0; i < 6; i++)
                {
                    _executorService.submit(NewInfiniteWaitingRunnable(exitCondition));
                }

                fail("should throw exception");
            }
            catch (RejectedExecutionException)
            {
                // expected
            }

            assertEquals(5, threadCounter.get());
        }
Exemplo n.º 17
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void shouldReadCorrectlyWithConcurrentUpdates(TestCoordinator testCoordinator) throws Throwable
        private void ShouldReadCorrectlyWithConcurrentUpdates(TestCoordinator testCoordinator)
        {
            // Readers config
            int readers = max(1, Runtime.Runtime.availableProcessors() - 1);

            // Thread communication
            System.Threading.CountdownEvent readerReadySignal = new System.Threading.CountdownEvent(readers);
            System.Threading.CountdownEvent readerStartSignal = new System.Threading.CountdownEvent(1);
            AtomicBoolean endSignal = testCoordinator.EndSignal();
            AtomicBoolean failHalt  = new AtomicBoolean();              // Readers signal to writer that there is a failure
            AtomicReference <Exception> readerError = new AtomicReference <Exception>();

            // GIVEN
            _index = CreateIndex();
            testCoordinator.Prepare(_index);

            // WHEN starting the readers
            RunnableReader readerTask = new RunnableReader(this, testCoordinator, readerReadySignal, readerStartSignal, endSignal, failHalt, readerError);

            for (int i = 0; i < readers; i++)
            {
                _threadPool.submit(readerTask);
            }

            // and starting the checkpointer
            _threadPool.submit(CheckpointThread(endSignal, readerError, failHalt));

            // and starting the writer
            try
            {
                Write(testCoordinator, readerReadySignal, readerStartSignal, endSignal, failHalt);
            }
            finally
            {
                // THEN no reader should have failed by the time we have finished all the scheduled updates.
                // A successful read means that all results were ordered and we saw all inserted values and
                // none of the removed values at the point of making the seek call.
                endSignal.set(true);
                _threadPool.shutdown();
                _threadPool.awaitTermination(10, TimeUnit.SECONDS);
                if (readerError.get() != null)
                {
                    //noinspection ThrowFromFinallyBlock
                    throw readerError.get();
                }
            }
        }
Exemplo n.º 18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 30_000) public void terminateExpiredTransaction() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TerminateExpiredTransaction()
        {
            using (Transaction transaction = Database.beginTx())
            {
                Database.createNode();
                transaction.Success();
            }

            ExpectedException.expectMessage("The transaction has been terminated.");

            using (Transaction transaction = Database.beginTx())
            {
                Node nodeById = Database.getNodeById(NODE_ID);
                nodeById.SetProperty("a", "b");
                _executor.submit(StartAnotherTransaction()).get();
            }
        }
Exemplo n.º 19
0
 protected internal override void DoStart()
 {
     lock (this)
     {
         _asyncLogProcessingExecutor.submit(_asyncEventProcessor);
         _asyncEventProcessor.awaitStartup();
     }
 }
Exemplo n.º 20
0
        public static Future <T> Future <T>(Callable <T> task)
        {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Future <T>      future   = executor.submit(task);

            executor.shutdown();
            return(future);
        }
Exemplo n.º 21
0
//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();
                }
            });
        }
Exemplo n.º 22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldWorkWithManyConcurrentProducers() throws java.util.concurrent.ExecutionException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void ShouldWorkWithManyConcurrentProducers()
        {
            // given
            int n          = 1000000;
            int bufferSize = 16;
            RingRecentBuffer <long> buffer   = new RingRecentBuffer <long>(bufferSize);
            ExecutorService         executor = Executors.newFixedThreadPool(4);

            try
            {
                // when
                // producer threads
                System.Threading.CountdownEvent latch = 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<?> produce1 = executor.submit(stressUntil(latch, buffer::produce));
                Future <object> produce1 = executor.submit(StressUntil(latch, buffer.produce));
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> produce2 = executor.submit(stressUntil(latch, buffer::produce));
                Future <object> produce2 = executor.submit(StressUntil(latch, buffer.produce));
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> produce3 = executor.submit(stressUntil(latch, buffer::produce));
                Future <object> produce3 = executor.submit(StressUntil(latch, buffer.produce));
                // consumer thread
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> consume = executor.submit(stress(n, i ->
                Future <object> consume = executor.submit(Stress(n, i =>
                {
                    buffer.Clear();
                    buffer.Foreach(Assertions.assertNotNull);
                }));

                // then without illegal transitions or exceptions
                consume.get();
                latch.Signal();
                produce1.get();
                produce2.get();
                produce3.get();
            }
            finally
            {
                executor.shutdown();
            }
            // on some systems thread scheduling variance actually causes ~100 silent drops in this test
            assertTrue(buffer.NumSilentQueryDrops() < 1000, "only a few silent drops expected");
        }
Exemplo n.º 23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void runTest() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RunTest()
        {
            for (int i = 0; i < N_THREADS; i++)
            {
                _service.submit(_task);
            }
            _service.awaitTermination(10, TimeUnit.SECONDS);
            assertThat(_counter.get(), equalTo(N_THREADS));
        }
Exemplo n.º 24
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void perform(Action action) throws Exception
        private void Perform(Action action)
        {
            ExecutorService service = Executors.newFixedThreadPool(_lifecycles.Count);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<java.util.concurrent.Future<?>> futures = new java.util.ArrayList<>();
            IList <Future <object> > futures = new List <Future <object> >();

            foreach (Lifecycle lifecycle in _lifecycles)
            {
                futures.Add(service.submit(() =>
                {
                    try
                    {
                        action.Act(lifecycle);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(e);
                    }
                }));
            }

            service.shutdown();
            if (!service.awaitTermination(_timeout, _unit))
            {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.concurrent.Future<?> future : futures)
                foreach (Future <object> future in futures)
                {
                    future.cancel(true);
                }
            }

            Exception exception = null;

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.concurrent.Future<?> future : futures)
            foreach (Future <object> future in futures)
            {
                try
                {
                    future.get();
                }
                catch (Exception e) when(e is InterruptedException || e is ExecutionException)
                {
                    if (exception == null)
                    {
                        exception = new Exception();
                    }
                    exception.addSuppressed(e);
                }
            }
            if (exception != null)
            {
                throw exception;
            }
        }
Exemplo n.º 25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void takeOrAwaitLatchMustNotLetUnrelatedLatchesConflictTooMuch() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void TakeOrAwaitLatchMustNotLetUnrelatedLatchesConflictTooMuch()
        {
            BinaryLatch latch = _latches.takeOrAwaitLatch(42);

            assertThat(latch, @is(notNullValue()));
            ExecutorService      executor = Executors.newSingleThreadExecutor();
            Future <BinaryLatch> future   = executor.submit(() => _latches.takeOrAwaitLatch(33));

            assertThat(future.get(1, TimeUnit.SECONDS), @is(notNullValue()));
            latch.Release();
        }
Exemplo n.º 26
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT) public void indexCreationDoNotBlockQueryExecutions() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void IndexCreationDoNotBlockQueryExecutions()
        {
            Label nodeLabel = Label.label("nodeLabel");

            using (Transaction transaction = _database.beginTx())
            {
                _database.createNode(nodeLabel);
                transaction.Success();
            }

            using (Transaction transaction = _database.beginTx())
            {
                _database.schema().indexFor(Label.label("testLabel")).on("testProperty").create();

                Future <Number> countFuture = _executorService.submit(CountNodes());
                assertEquals(1, countFuture.get().intValue());

                transaction.Success();
            }
        }
Exemplo n.º 27
0
        internal override ExecutorService SetupWorkload(int n)
        {
            ExecutorService service   = Executors.newFixedThreadPool(n);
            ISet <string>   usernames = MakeWithPrefix("user", n);
            ISet <string>   roleNames = MakeWithPrefix("role", n);

            for (int i = 0; i < n; i++)
            {
                service.submit(new ChaoticAdmin(this, i, usernames, roleNames));
            }
            return(service);
        }
Exemplo n.º 28
0
        private Future <Void> KillDbInSeparateThread()
        {
            ExecutorService executor = newSingleThreadExecutor();
            Future <Void>   result   = executor.submit(() =>
            {
                KillDb();
                return(null);
            });

            executor.shutdown();
            return(result);
        }
Exemplo n.º 29
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void shouldNotReadSameElementTwice() throws java.util.concurrent.ExecutionException, InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void ShouldNotReadSameElementTwice()
        {
            // given
            int n          = 1000;
            int bufferSize = 16;
            RingRecentBuffer <long> buffer   = new RingRecentBuffer <long>(bufferSize);
            ExecutorService         executor = Executors.newFixedThreadPool(2);

            try
            {
                UniqueElementsConsumer consumer = new UniqueElementsConsumer();

                // when
                // producer thread
                System.Threading.CountdownEvent latch = 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<?> produce = executor.submit(stressUntil(latch, buffer::produce));
                Future <object> produce = executor.submit(StressUntil(latch, buffer.produce));

                // consumer thread
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> consume = executor.submit(stress(n, i ->
                Future <object> consume = executor.submit(Stress(n, i =>
                {
                    consumer.Reset();
                    buffer.Foreach(consumer);
                    assertTrue(consumer.Values.size() <= bufferSize, format("Should see at most %d elements", bufferSize));
                }));

                // then without illegal transitions or exceptions
                consume.get();
                latch.Signal();
                produce.get();
            }
            finally
            {
                executor.shutdown();
            }
            assertEquals(0, buffer.NumSilentQueryDrops());
        }
Exemplo n.º 30
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void releaseMustUnblockAwaiters()
        internal virtual void ReleaseMustUnblockAwaiters()
        {
            assertTimeout(ofSeconds(10), () =>
            {
                BinaryLatch latch         = new BinaryLatch();
                ThreadStart awaiter       = latch.await;
                int awaiters              = 24;
                Future <object>[] futures = new Future <object> [awaiters];
                for (int i = 0; i < awaiters; i++)
                {
                    futures[i] = _executor.submit(awaiter);
                }

                assertThrows(typeof(TimeoutException), () => futures[0].get(10, TimeUnit.MILLISECONDS));

                latch.Release();

                foreach (Future <object> future in futures)
                {
                    future.get();
                }
            });
        }