Ejemplo n.º 1
0
        /// <summary>
        /// Awaits completion of this population job, but waits maximum the given time.
        /// </summary>
        /// <param name="time"> time to wait at the most for completion. A value of 0 means indefinite wait. </param>
        /// <param name="unit"> <seealso cref="TimeUnit unit"/> of the {@code time}. </param>
        /// <returns> {@code true} if the job is still running when leaving this method, otherwise {@code false} meaning that the job is completed. </returns>
        /// <exception cref="InterruptedException"> if the wait got interrupted. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public boolean awaitCompletion(long time, java.util.concurrent.TimeUnit unit) throws InterruptedException
        public virtual bool AwaitCompletion(long time, TimeUnit unit)
        {
            if (time == 0)
            {
                _doneSignal.await();
                return(false);
            }
            bool completed = _doneSignal.await(time, unit);

            return(!completed);
        }
Ejemplo n.º 2
0
//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
        }
Ejemplo n.º 3
0
//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());
        }
Ejemplo n.º 4
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void await(String message, long timeout, java.util.concurrent.TimeUnit timeUnit) throws InterruptedException
            public virtual void Await(string message, long timeout, TimeUnit timeUnit)
            {
                if (!ReaperLatch.await(timeout, timeUnit))
                {
                    throw new System.InvalidOperationException(message);
                }
            }
Ejemplo n.º 5
0
//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());
            });
        }
Ejemplo n.º 6
0
//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();
        }
Ejemplo n.º 7
0
//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);
            }
        }
Ejemplo n.º 8
0
        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.");
        }
Ejemplo n.º 9
0
//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
        }
Ejemplo n.º 10
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);
            }
        }
Ejemplo n.º 11
0
//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();
        }
Ejemplo n.º 12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldReturnCorrectStatusCodeOnDeadlock() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldReturnCorrectStatusCodeOnDeadlock()
        {
            // Given
            using (Transaction tx = Graphdb().beginTx())
            {
                Graphdb().createNode(Label.label("First"));
                Graphdb().createNode(Label.label("Second"));
                tx.Success();
            }

            // When I lock node:First
            HTTP.Response begin = _http.POST("db/data/transaction", quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:First) SET n.prop=1' } ] }"));

            // and I lock node:Second, and wait for a lock on node:First in another transaction
            OtherThread.execute(WriteToFirstAndSecond());

            // and I wait for those locks to be pending
            assertTrue(_secondNodeLocked.await(10, TimeUnit.SECONDS));
            Thread.Sleep(1000);

            // and I then try and lock node:Second in the first transaction
            HTTP.Response deadlock = _http.POST(begin.Location(), quotedJson("{ 'statements': [ { 'statement': 'MATCH (n:Second) SET n.prop=1' } ] }"));

            // Then
            assertThat(deadlock.Get("errors").get(0).get("code").TextValue, equalTo(DeadlockDetected.code().serialize()));
        }
Ejemplo n.º 13
0
//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);
            }
        }
Ejemplo n.º 14
0
//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));
        }
Ejemplo n.º 15
0
//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)));
        }
Ejemplo n.º 16
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();
                }
            });
        }
Ejemplo n.º 17
0
//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();
        }
Ejemplo n.º 18
0
//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();
            }
        }
Ejemplo n.º 19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public TYPE get() throws Exception
            public override TYPE Get()
            {
                Latch.await();
                if (Failure != null)
                {
                    throw Failure;
                }
                return(Value);
            }
Ejemplo n.º 20
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);
        }
Ejemplo n.º 21
0
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
 //ORIGINAL LINE: public Void answer(org.mockito.invocation.InvocationOnMock invocation) throws Throwable
 public override Void Answer( InvocationOnMock invocation )
 {
     // releasing reader after local lock released
         ResourceLatch.Signal();
         // waiting here for reader to finish read lock acquisition.
         // by this we check that local exclusive lock where released before releasing it on
         // master otherwise reader will be blocked forever
         ResourceReleaseLatch.await();
         return null;
 }
Ejemplo n.º 22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldReclaimAndRecreateWhenUsageGoesDownBetweenSpikes() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldReclaimAndRecreateWhenUsageGoesDownBetweenSpikes()
        {
            // given
            const int poolMinSize = 50;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int bellowPoolMinSize = poolMinSize / 5;
            int       bellowPoolMinSize = poolMinSize / 5;
            const int poolMaxSize       = 200;

            StatefulMonitor stateMonitor = new StatefulMonitor(this);
            FakeClock       clock        = FakeClocks;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final SomethingResourcePool pool = getResourcePool(stateMonitor, clock, poolMinSize);
            SomethingResourcePool pool = GetResourcePool(stateMonitor, clock, poolMinSize);

            AcquireResourcesAndExceedTimeout(pool, clock, poolMaxSize);

            // when
            // After the peak, stay well below concurrent usage, using up all already present resources in the process
            ExceedTimeout(clock);
            // Requires some rounds to happen, since there is constant racing between releasing and acquiring which does
            // not always result in reaping of resources, as there is reuse
            for (int i = 0; i < 30; i++)
            {
                // The latch is necessary to reduce races between batches
                System.Threading.CountdownEvent release = new System.Threading.CountdownEvent(bellowPoolMinSize);
                foreach (ResourceHolder holder in AcquireFromPool(pool, bellowPoolMinSize))
                {
                    holder.Release(release);
                }
                release.await();
                ExceedTimeout(clock);
            }

            // then
            // currentPeakSize should not be higher than bellowPoolMinSize
            assertTrue(stateMonitor.CurrentPeakSize.get().ToString(), stateMonitor.CurrentPeakSize.get() <= bellowPoolMinSize);
            // target size should remain at pool min size
            assertEquals(poolMinSize, stateMonitor.TargetSize.get());
            assertEquals(poolMinSize, pool.UnusedSize());
            // only the excess from the pool max size down to min size must have been disposed
            // +1 that was used to trigger initial exceed timeout check
            assertEquals(poolMaxSize - poolMinSize + 1, stateMonitor.DisposedConflict.get());

            stateMonitor.CreatedConflict.set(0);
            stateMonitor.DisposedConflict.set(0);

            // when
            // After the lull, recreate a peak
            AcquireResourcesAndExceedTimeout(pool, clock, poolMaxSize);

            // then
            assertEquals(poolMaxSize - poolMinSize + 1, stateMonitor.CreatedConflict.get());
            assertEquals(0, stateMonitor.DisposedConflict.get());
        }
Ejemplo n.º 23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = TEST_TIMEOUT_MILLIS) public void testLockRequestsTermination() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TestLockRequestsTermination()
        {
            // given
            RagManager   ragManager = new RagManager();
            LockResource node1      = new LockResource(ResourceTypes.NODE, 1L);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final RWLock lock = createRWLock(ragManager, node1);
            RWLock @lock = CreateRWLock(ragManager, node1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockTransaction mainTransaction = new LockTransaction();
            LockTransaction mainTransaction = new LockTransaction();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockTransaction writerTransaction = new LockTransaction();
            LockTransaction writerTransaction = 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);
            ThreadStart conflictingWriter = CreateFailedWriter(@lock, writerTransaction, writerCompletedLatch);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockTransaction readerTransaction = new LockTransaction();
            LockTransaction readerTransaction = new LockTransaction();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch readerCompletedLatch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent readerCompletedLatch = new System.Threading.CountdownEvent(1);
            ThreadStart reader = CreateFailedReader(@lock, readerTransaction, readerCompletedLatch);

            // when
            @lock.Mark();
            assertTrue(@lock.AcquireWriteLock(LockTracer.NONE, mainTransaction));
            _executor.submit(reader);
            _executor.submit(conflictingWriter);

            // wait waiters to come
            WaitWaitingThreads(@lock, 2);
            assertEquals(3, @lock.TxLockElementCount);

            // when
            @lock.TerminateLockRequestsForLockTransaction(readerTransaction);
            @lock.TerminateLockRequestsForLockTransaction(writerTransaction);

            readerCompletedLatch.await();
            writerCompletedLatch.await();

            // expect only main write lock counters and elements present
            // all the rest should be cleaned up
            assertEquals(0, @lock.WaitingThreadsCount);
            assertEquals(0, @lock.ReadCount);
            assertEquals(1, @lock.WriteCount);
            assertEquals(1, @lock.TxLockElementCount);
        }
Ejemplo n.º 24
0
 public override void Run()
 {
     try
     {
         ExecutionLatch.await();
     }
     catch (InterruptedException e)
     {
         throw new Exception("Interrupted while waiting for a latch", e);
     }
 }
Ejemplo n.º 25
0
 internal virtual void AwaitStartSignal()
 {
     try
     {
         StartSignal.await(10, SECONDS);
     }
     catch (InterruptedException e)
     {
         throw new Exception(e);
     }
 }
Ejemplo n.º 26
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void write(TestCoordinator testCoordinator, java.util.concurrent.CountDownLatch readerReadySignal, java.util.concurrent.CountDownLatch readerStartSignal, java.util.concurrent.atomic.AtomicBoolean endSignal, java.util.concurrent.atomic.AtomicBoolean failHalt) throws InterruptedException, java.io.IOException
        private void Write(TestCoordinator testCoordinator, System.Threading.CountdownEvent readerReadySignal, System.Threading.CountdownEvent readerStartSignal, AtomicBoolean endSignal, AtomicBoolean failHalt)
        {
            assertTrue(readerReadySignal.await(10, SECONDS)); // Ready, set...
            readerStartSignal.Signal();                       // GO!

            while (!failHalt.get() && !endSignal.get())
            {
                WriteOneIteration(testCoordinator, failHalt);
                testCoordinator.IterationFinished();
            }
        }
Ejemplo n.º 27
0
 public override void outputFileCreated(Stream @out)
 {
     try
     {
         _allowRotationComplete.await();
     }
     catch (InterruptedException e)
     {
         throw new Exception(e);
     }
 }
Ejemplo n.º 28
0
 private void Await(System.Threading.CountdownEvent latch)
 {
     try
     {
         assertTrue(latch.await(1, TimeUnit.MINUTES));
     }
     catch (InterruptedException e)
     {
         throw new AssertionError(e);
     }
 }
//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();
            }
        }
Ejemplo n.º 30
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public Action next() throws InterruptedException
        public virtual Action Next()
        {
            _startLatch.await();
            int index = _actionCounter.AndIncrement;

            if (index < _plan.Length)
            {
                _executedByThread[index] = Thread.CurrentThread.Id;
                return(_plan[index]);
            }
            return(null);
        }