Beispiel #1
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testConcurrentIsUserAuthorized() throws Exception
        public virtual void testConcurrentIsUserAuthorized()
        {
            int             threadCount     = 2;
            int             invocationCount = 500;
            ExecutorService executorService = Executors.newFixedThreadPool(threadCount);

            try
            {
                List <Callable <Exception> > callables = new List <Callable <Exception> >();

                for (int i = 0; i < invocationCount; i++)
                {
                    callables.Add(new CallableAnonymousInnerClass(this));
                }

                IList <Future <Exception> > futures = executorService.invokeAll(callables);

                foreach (Future <Exception> future in futures)
                {
                    Exception exception = future.get();
                    if (exception != null)
                    {
                        fail("No exception expected: " + exception.Message);
                    }
                }
            }
            finally
            {
                // reset original logging level
                executorService.shutdownNow();
                executorService.awaitTermination(10, TimeUnit.SECONDS);
            }
        }
Beispiel #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void mustNotLeakTasksOnCrash()
        public virtual void MustNotLeakTasksOnCrash()
        {
            // Given
            string exceptionMessage                = "When there's no more room in hell, the dead will walk the earth";
            CrashGenerationCleaner cleaner         = NewCrashingCrashGenerationCleaner(exceptionMessage);
            ExecutorService        executorService = Executors.newFixedThreadPool(Runtime.Runtime.availableProcessors());

            try
            {
                // When
                cleaner.Clean(executorService);
                fail("Expected to throw");
            }
            catch (Exception e)
            {
                Exception rootCause = Exceptions.rootCause(e);
                assertTrue(rootCause is IOException);
                assertEquals(exceptionMessage, rootCause.Message);
            }
            finally
            {
                // Then
                IList <ThreadStart> tasks = executorService.shutdownNow();
                assertEquals(0, tasks.Count);
            }
        }
Beispiel #3
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();
            }
        }
Beispiel #4
0
        private void ShutdownExecutorAndVerifyNoLeaks(ExecutorService executor)
        {
            IList <ThreadStart> leakedTasks = executor.shutdownNow();

            if (leakedTasks.Count != 0)
            {
                throw new System.InvalidOperationException("Tasks leaked from CleanupJob. Tasks where " + leakedTasks.ToString());
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeOut = 5000) public void interruptHangingResultsListener() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
        public virtual void interruptHangingResultsListener()
        {
            HangingFunction     fn   = new HangingFunction();
            CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL);
            CalculationTask     task = CalculationTask.of(TARGET, fn, cell);
            Column           column  = Column.of(TestingMeasures.PRESENT_VALUE);
            CalculationTasks tasks   = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column));

            ExecutorService executor = Executors.newSingleThreadExecutor();

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

                AtomicBoolean shouldNeverComplete    = new AtomicBoolean();
                AtomicBoolean interrupted            = new AtomicBoolean();
                AtomicReference <Exception> thrown   = new AtomicReference <Exception>();
                ResultsListener             listener = new ResultsListener();
                test.calculateAsync(tasks, marketData, REF_DATA, listener);
                System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
                Thread thread = new Thread(() =>
                {
                    try
                    {
                        listener.result();
                        shouldNeverComplete.set(true);
                    }
                    catch (Exception ex)
                    {
                        interrupted.set(Thread.CurrentThread.Interrupted);
                        thrown.set(ex);
                    }
                    latch.Signal();
                });
                // run the thread, wait until properly started, then interrupt, wait until properly handled
                thread.Start();
                while (!fn.started)
                {
                }
                thread.Interrupt();
                latch.await();
                // asserts
                assertEquals(interrupted.get(), true);
                assertEquals(shouldNeverComplete.get(), false);
                assertEquals(thrown.get() is Exception, true);
                assertEquals(thrown.get().Cause is InterruptedException, true);
            }
            finally
            {
                executor.shutdownNow();
            }
        }
Beispiel #6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRunSimpleStatement() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRunSimpleStatement()
        {
            // Given
            int numWorkers  = 5;
            int numRequests = 1_000;

            IList <Callable <Void> > workers = CreateWorkers(numWorkers, numRequests);
            ExecutorService          exec    = Executors.newFixedThreadPool(numWorkers);

            try
            {
                // When & then
                foreach (Future <Void> f in exec.invokeAll(workers))
                {
                    f.get(60, TimeUnit.SECONDS);
                }
            }
            finally
            {
                exec.shutdownNow();
                exec.awaitTermination(30, TimeUnit.SECONDS);
            }
        }
Beispiel #7
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @After public void consistencyCheckAndClose() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConsistencyCheckAndClose()
        {
            _threadPool.shutdownNow();
            _index.consistencyCheck();
            _index.Dispose();
        }
Beispiel #8
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void shouldShutdownEvenThoughWaitingForLock0(org.neo4j.causalclustering.discovery.Cluster<?> cluster, int victimId, java.util.Collection<int> shutdownOrder) throws Exception
        private void ShouldShutdownEvenThoughWaitingForLock0 <T1>(Cluster <T1> cluster, int victimId, ICollection <int> shutdownOrder)
        {
            const int longTime = 60_000;
            const int numberOfLockAcquirers = 2;

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.ExecutorService txExecutor = java.util.concurrent.Executors.newCachedThreadPool();
            ExecutorService txExecutor = Executors.newCachedThreadPool();               // Blocking transactions are executed in
            // parallel, not on the main thread.
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.ExecutorService shutdownExecutor = java.util.concurrent.Executors.newFixedThreadPool(1);
            ExecutorService shutdownExecutor = Executors.newFixedThreadPool(1);                 // Shutdowns are executed

            // serially, not on the main thread.

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch acquiredLocksCountdown = new java.util.concurrent.CountDownLatch(NUMBER_OF_LOCK_ACQUIRERS);
            System.Threading.CountdownEvent acquiredLocksCountdown = new System.Threading.CountdownEvent(numberOfLockAcquirers);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch locksHolder = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent locksHolder = 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.Node> node = new java.util.concurrent.atomic.AtomicReference<>();
            AtomicReference <Node> node = new AtomicReference <Node>();

            CompletableFuture <Void> preShutdown = new CompletableFuture <Void>();

            // set shutdown order
            CompletableFuture <Void> afterShutdown = preShutdown;

            foreach (int?id in shutdownOrder)
            {
                afterShutdown = afterShutdown.thenRunAsync(() => cluster.GetCoreMemberById(id.Value).shutdown(), shutdownExecutor);
            }

            CreateANode(node);

            try
            {
                // when - blocking on lock acquiring
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.graphdb.GraphDatabaseService leader = cluster.getCoreMemberById(victimId).database();
                GraphDatabaseService leader = cluster.GetCoreMemberById(victimId).database();

                for (int i = 0; i < numberOfLockAcquirers; i++)
                {
                    txExecutor.execute(() =>
                    {
                        try
                        {
                            using (Transaction tx = leader.BeginTx())
                            {
                                acquiredLocksCountdown.Signal();
                                tx.acquireWriteLock(node.get());
                                locksHolder.await();
                                tx.success();
                            }
                        }
                        catch (Exception)
                        {
                            /* Since we are shutting down, a plethora of possible exceptions are expected. */
                        }
                    });
                }

                // await locks
                if (!acquiredLocksCountdown.await(longTime, MILLISECONDS))
                {
                    throw new System.InvalidOperationException("Failed to acquire locks");
                }

                // then shutdown in given order works
                preShutdown.complete(null);
                afterShutdown.get(longTime, MILLISECONDS);
            }
            finally
            {
                afterShutdown.cancel(true);
                locksHolder.Signal();
                txExecutor.shutdownNow();
                shutdownExecutor.shutdownNow();
            }
        }
Beispiel #9
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: static void stressTest(Config config, org.neo4j.io.fs.FileSystemAbstraction fileSystem, org.neo4j.io.pagecache.PageCache pageCache) throws Exception
        internal static void StressTest(Config config, FileSystemAbstraction fileSystem, PageCache pageCache)
        {
            Resources resources = new Resources(fileSystem, pageCache, config);
            Control   control   = new Control(config);
            Log       log       = config.LogProvider().getLog(typeof(ClusterStressTesting));

            log.Info(config.ToString());

            IList <Preparation> preparations = config.Preparations().Select(preparation => preparation.create(resources)).ToList();

            IList <Workload> workloads = config.Workloads().Select(workload => workload.create(control, resources, config)).ToList();

            IList <Validation> validations = config.Validations().Select(validator => validator.create(resources)).ToList();

            if (workloads.Count == 0)
            {
                throw new System.ArgumentException("No workloads.");
            }

            ExecutorService executor = Executors.newCachedThreadPool();

            try
            {
                log.Info("Starting resources");
                resources.Start();

                log.Info("Preparing scenario");
                foreach (Preparation preparation in preparations)
                {
                    preparation.Prepare();
                }

                log.Info("Preparing workloads");
                foreach (Workload workload in workloads)
                {
                    workload.Prepare();
                }

                log.Info("Starting workloads");
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<java.util.concurrent.Future<?>> completions = new java.util.ArrayList<>();
                IList <Future <object> > completions = new List <Future <object> >();
                foreach (Workload workload in workloads)
                {
                    completions.Add(executor.submit(workload));
                }

                control.AwaitEnd(completions);

                foreach (Workload workload in workloads)
                {
                    workload.Validate();
                }
            }
            catch (Exception cause)
            {
                control.OnFailure(cause);
            }

            log.Info("Shutting down executor");
            executor.shutdownNow();
            executor.awaitTermination(5, TimeUnit.MINUTES);

            log.Info("Stopping resources");
            resources.Stop();

            control.AssertNoFailure();

            log.Info("Validating results");
            foreach (Validation validation in validations)
            {
                validation.Validate();
            }

            // let us only cleanup resources when everything went well, and otherwise leave them for post-mortem
            log.Info("Cleaning up");
            resources.Cleanup();
        }