Пример #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldStopLockSessionOnFailureWhereThereIsAnActiveLockAcquisition()
        {
            // GIVEN
            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            try
            {
                Locks_Client    client    = NewWaitingLocksClient(latch);
                MasterImpl      master    = NewMasterWithLocksClient(client);
                HandshakeResult handshake = master.Handshake(1, newStoreIdForCurrentVersion()).response();

                // WHEN
                RequestContext context = new RequestContext(handshake.Epoch(), 1, 2, 0, 0);
                master.NewLockSession(context);
                Future <Void> acquireFuture = OtherThread.execute(state =>
                {
                    master.AcquireExclusiveLock(context, ResourceTypes.NODE, 1L);
                    return(null);
                });
                OtherThread.get().waitUntilWaiting();
                master.EndLockSession(context, false);
                verify(client).stop();
                verify(client, never()).close();
                latch.Signal();
                acquireFuture.get();

                // THEN
                verify(client).close();
            }
            finally
            {
                latch.Signal();
            }
        }
Пример #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 10000) public void logRotationMustNotObstructStartingReadTransaction()
        public virtual void LogRotationMustNotObstructStartingReadTransaction()
        {
            using (Transaction tx = Db.beginTx())
            {
                Db.getNodeById(0);
                tx.Success();
                _completeLogRotationLatch.Signal();
            }
        }
Пример #3
0
        public async Task CallService(HttpContext context)
        {
            _waitUntilRequestsAreFinished.AddCount();
            try
            {
                var uriString = $"http://{_hostString}{context.Request.Path}{context.Request.QueryString}";
                var uri       = new Uri(uriString);

                var requestMessage = new HttpRequestMessage();
                if (!string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase) &&
                    !string.Equals(context.Request.Method, "HEAD", StringComparison.OrdinalIgnoreCase) &&
                    !string.Equals(context.Request.Method, "DELETE", StringComparison.OrdinalIgnoreCase) &&
                    !string.Equals(context.Request.Method, "TRACE", StringComparison.OrdinalIgnoreCase))
                {
                    var streamContent = new StreamContent(context.Request.Body);
                    requestMessage.Content = streamContent;
                }
                requestMessage.RequestUri = uri;
                requestMessage.Method     = new HttpMethod(context.Request.Method);
                // Copy the request headers
                foreach (var header in context.Request.Headers)
                {
                    if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()) && requestMessage.Content != null)
                    {
                        requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                    }
                }

                requestMessage.Headers.Host = _hostString;

                requestMessage.Method = new HttpMethod(context.Request.Method);

                using (var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
                {
                    context.Response.StatusCode = (int)responseMessage.StatusCode;
                    foreach (var header in responseMessage.Headers)
                    {
                        context.Response.Headers[header.Key] = header.Value.ToArray();
                    }

                    foreach (var header in responseMessage.Content.Headers)
                    {
                        context.Response.Headers[header.Key] = header.Value.ToArray();
                    }

                    // SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
                    context.Response.Headers.Remove("transfer-encoding");
                    await responseMessage.Content.CopyToAsync(context.Response.Body);
                }
            }
            finally
            {
                _waitUntilRequestsAreFinished.Signal();
            }
        }
Пример #4
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldHaveConfigurableJettyThreadPoolSize() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldHaveConfigurableJettyThreadPoolSize()
        {
            Jetty9WebServer server               = new Jetty9WebServer(NullLogProvider.Instance, Config.defaults(), NetworkConnectionTracker.NO_OP);
            int             numCores             = 1;
            int             configuredMaxThreads = 12;                                                       // 12 is the new min max Threads value, for one core
            int             acceptorThreads      = 1;                                                        // In this configuration, 1 thread will become an acceptor...
            int             selectorThreads      = 1;                                                        // ... and 1 thread will become a selector...
            int             jobThreads           = configuredMaxThreads - acceptorThreads - selectorThreads; // ... and the rest are job threads

            server.MaxThreads  = numCores;
            server.HttpAddress = new ListenSocketAddress("localhost", 0);
            try
            {
                server.Start();
                QueuedThreadPool threadPool = ( QueuedThreadPool )server.Jetty.ThreadPool;
                threadPool.start();
                System.Threading.CountdownEvent startLatch = new System.Threading.CountdownEvent(jobThreads);
                System.Threading.CountdownEvent endLatch   = LoadThreadPool(threadPool, configuredMaxThreads + 1, startLatch);
                startLatch.await();                         // Wait for threadPool to create threads
                int threads = threadPool.Threads;
                assertEquals("Wrong number of threads in pool", configuredMaxThreads, threads);
                endLatch.Signal();
            }
            finally
            {
                server.Stop();
            }
        }
Пример #5
0
        private void SendCommandASynch()
        {
            countDown = new System.Threading.CountdownEvent(1);

            foreach (DataGridViewRow row in dgvComputers.Rows)
            {
                if (!_closing && !_wrongCrendentialsWatcher.IsAbortRequested)
                {
                    countDown.AddCount();
                    CommandParameters parameters = GetCommonParameters();
                    parameters.Row            = row;
                    parameters.TargetComputer = (ADComputer)row.Cells["ADComputer"].Value;

                    parameters.Login    = _login;
                    parameters.Password = _password;
                    System.Threading.ThreadPool.QueueUserWorkItem(SendCommandToComputer, (object)parameters);
                }
            }
            countDown.Signal();
            countDown.Wait(5000 * dgvComputers.Rows.Count);
            DisplayProgress();
            Action action = () =>
            {
                dgvComputers.Sort(dgvComputers.Columns["Result"], ListSortDirection.Descending);
                btnClose.Enabled = true;
                btnAbort.Enabled = false;
            };

            if (!_closing)
            {
                this.Invoke(action);
            }
        }
        public virtual void test_toCombinedFutureMap()
        {
            CompletableFuture <string> future1 = new CompletableFuture <string>();

            future1.complete("A");
            System.Threading.CountdownEvent latch   = new System.Threading.CountdownEvent(1);
            CompletableFuture <string>      future2 = CompletableFuture.supplyAsync(() =>
            {
                try
                {
                    latch.await();
                }
                catch (InterruptedException)
                {
                }
                return("B");
            });
            IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2);

//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            CompletableFuture <IDictionary <string, string> > test = input.SetOfKeyValuePairs().collect(Guavate.toCombinedFutureMap());

            assertEquals(test.Done, false);
            latch.Signal();
            IDictionary <string, string> combined = test.join();

            assertEquals(test.Done, true);
            assertEquals(combined.Count, 2);
            assertEquals(combined["a"], "A");
            assertEquals(combined["b"], "B");
        }
        //-------------------------------------------------------------------------
        public virtual void test_combineFuturesAsMap()
        {
            CompletableFuture <string> future1 = new CompletableFuture <string>();

            future1.complete("A");
            System.Threading.CountdownEvent latch   = new System.Threading.CountdownEvent(1);
            CompletableFuture <string>      future2 = CompletableFuture.supplyAsync(() =>
            {
                try
                {
                    latch.await();
                }
                catch (InterruptedException)
                {
                }
                return("B");
            });
            IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2);

            CompletableFuture <IDictionary <string, string> > test = Guavate.combineFuturesAsMap(input);

            assertEquals(test.Done, false);
            latch.Signal();
            IDictionary <string, string> combined = test.join();

            assertEquals(test.Done, true);
            assertEquals(combined.Count, 2);
            assertEquals(combined["a"], "A");
            assertEquals(combined["b"], "B");
        }
Пример #8
0
 public override void FileModified(string fileName)
 {
     if (ExpectedFileName.Equals(fileName))
     {
         ModificationLatch.Signal();
     }
 }
Пример #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndexWhereLogHasRotated() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBeAbleToRecoverInTheMiddleOfPopulatingAnIndexWhereLogHasRotated()
        {
            // Given
            StartDb();

            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            when(_mockedIndexProvider.getPopulator(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig)), any())).thenReturn(IndexPopulatorWithControlledCompletionTiming(latch));
            CreateIndex(_myLabel);
            RotateLogsAndCheckPoint();

            // And Given
            Future <Void> killFuture = KillDbInSeparateThread();

            latch.Signal();
            killFuture.get();
            latch = new System.Threading.CountdownEvent(1);
            when(_mockedIndexProvider.getPopulator(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig)), any())).thenReturn(IndexPopulatorWithControlledCompletionTiming(latch));
            when(_mockedIndexProvider.getInitialState(any(typeof(StoreIndexDescriptor)))).thenReturn(InternalIndexState.POPULATING);

            // When
            StartDb();

            // Then
            assertThat(getIndexes(_db, _myLabel), inTx(_db, hasSize(1)));
            assertThat(getIndexes(_db, _myLabel), inTx(_db, haveState(_db, Org.Neo4j.Graphdb.schema.Schema_IndexState.Populating)));
            verify(_mockedIndexProvider, times(2)).getPopulator(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig)), any());
            verify(_mockedIndexProvider, never()).getOnlineAccessor(any(typeof(StoreIndexDescriptor)), any(typeof(IndexSamplingConfig)));
            latch.Signal();
        }
Пример #10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldMutexAccessBetweenInvalidateAndinstance() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldMutexAccessBetweenInvalidateAndinstance()
        {
            // GIVEN
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch latch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicInteger initCalls = new java.util.concurrent.atomic.AtomicInteger();
            AtomicInteger             initCalls = new AtomicInteger();
            LazySingleReference <int> @ref      = new LazySingleReferenceAnonymousInnerClass2(this, latch, initCalls);
            Future <int> t1Evaluate             = _t1.executeDontWait(Evaluate(@ref));

            _t1.waitUntilWaiting();

            // WHEN
            Future <Void> t2Invalidate = _t2.executeDontWait(Invalidate(@ref));

            _t2.waitUntilBlocked();
            latch.Signal();
            int e = t1Evaluate.get();

            t2Invalidate.get();

            // THEN
            assertEquals("Evaluation", 1, e);
        }
Пример #11
0
 public override void FileDeleted(string fileName)
 {
     if (fileName.EndsWith(ExpectedFileName, StringComparison.Ordinal))
     {
         DeletionLatch.Signal();
     }
 }
Пример #12
0
        public virtual void test_combineFuturesAsMap_exception()
        {
            CompletableFuture <string> future1 = new CompletableFuture <string>();

            future1.complete("A");
            System.Threading.CountdownEvent latch   = new System.Threading.CountdownEvent(1);
            CompletableFuture <string>      future2 = CompletableFuture.supplyAsync(() =>
            {
                try
                {
                    latch.await();
                }
                catch (InterruptedException)
                {
                }
                throw new System.InvalidOperationException("Oops");
            });
            IDictionary <string, CompletableFuture <string> > input = ImmutableMap.of("a", future1, "b", future2);

            CompletableFuture <IDictionary <string, string> > test = Guavate.combineFuturesAsMap(input);

            assertEquals(test.Done, false);
            latch.Signal();
            assertThrows(typeof(CompletionException), () => test.join());
            assertEquals(test.Done, true);
            assertEquals(test.CompletedExceptionally, true);
        }
Пример #13
0
 public override void TearDownPageCache(MuninnPageCache pageCache)
 {
     if (BackgroundFlushLatch != null)
     {
         BackgroundFlushLatch.Signal();
         BackgroundFlushLatch = null;
     }
     pageCache.Close();
     _allocator.close();
 }
Пример #14
0
        public void TestRunTwoExperimentsSimultanouslyAndTerminateOneExperiment()
        {
            //assure workspace is empty
            AppContext.WorkspaceInstance.Clear();

            var done = new System.Threading.CountdownEvent(2);

            //start experiment one (takes more than 2 seconds to finish successfully)
            Experiment   experimentOne = LoadExperiment("long-experiment.teml");
            MockProgress progressOne   = new MockProgress();

            experimentOne.RunExperiment(progressOne, AppContext.WorkspaceInstance, AppContext.Components);
            experimentOne.ExperimentCompleted += (sender, args) =>
            {
                done.Signal();
            };

            //start experiment two and terminate it
            MockProgress progressTwo   = new MockProgress();
            Experiment   experimentTwo = LoadExperiment("infinite_loop_terminate_experiment_test.teml");

            experimentTwo.RunExperiment(progressTwo, AppContext.WorkspaceInstance, AppContext.Components);
            experimentTwo.ExperimentStarted += (sender, args) =>
            {
                experimentTwo.StopRunningExperiment();
            };
            experimentTwo.ExperimentCompleted += (sender, args) =>
            {
                done.Signal();
            };

            //wait for both experiment to end
            done.Wait(5000);

            //the experiment one should have ended successfully (it SHOULD NOT have been terminated)
            Assert.IsFalse(progressOne.HasError);
            Assert.AreEqual(Messages.ExperimentRunnerSuccessMessage, progressOne.CurrentStatus);

            //while exepriment two should be terminated
            Assert.IsTrue(progressTwo.HasError);
            Assert.AreEqual(Messages.ExperimentExecutionTerminated, progressTwo.CurrentStatus);
        }
Пример #15
0
 public override void failed(InstanceId server)
 {
     if (InstanceIdOf(_slave1).Equals(server))
     {
         _slave1Left.Signal();
     }
     else if (InstanceIdOf(_slave2).Equals(server))
     {
         _slave2Left.Signal();
     }
 }
Пример #16
0
 public override void memberIsUnavailable(string role, InstanceId unavailableId)
 {
     if (InstanceIdOf(_newSlave1).Equals(unavailableId))
     {
         _slave1Unavailable.Signal();
     }
     else if (InstanceIdOf(_newSlave2).Equals(unavailableId))
     {
         _slave2Unavailable.Signal();
     }
 }
Пример #17
0
        internal void RegisterCoreMember(SharedDiscoveryCoreClient client)
        {
            CoreServerInfo previousMember = _coreMembers.putIfAbsent(client.MemberId, client.CoreServerInfo);

            if (previousMember == null)
            {
                _listeningClients.Add(client);
                _enoughMembers.Signal();
                NotifyCoreClients();
            }
        }
        private void SendCommandToComputer(object data)
        {
            ADComputer      computer        = null;
            DataForComputer dataForComputer = (DataForComputer)data;
            DataGridViewRow row             = dataForComputer.Row;

            String[] options = dataForComputer.Options;
            System.Threading.CountdownEvent countDown = dataForComputer.CountDown;

            try
            {
                Action startAction = () =>
                {
                    lock (dtGrvComputers)
                    {
                        if (!_closing && !_aborting)
                        {
                            row.Cells["Status"].Value = resMan.GetString("SendingCommand");
                            computer = (ADComputer)row.Cells["Computer"].Value;
                        }
                    }
                    Logger.Write("Will try to send InstallPendingUpdates on : " + computer.Name);
                };
                if (!_closing && !_aborting)
                {
                    this.Invoke(startAction);
                }

                ADComputer.InstallPendingUpdatesResult result = ADComputer.InstallPendingUpdatesResult.FailToSendCommand;
                if (!_closing && !_aborting)
                {
                    result = computer.InstallPendingUpdates(options, Username, Password);
                }

                Action endAction = () =>
                {
                    Logger.Write("Result for " + computer.Name + " is : " + result.ToString());

                    lock (dtGrvComputers)
                    {
                        if (!_closing && !_aborting)
                        {
                            row.Cells["Status"].Value = resMan.GetString(result.ToString());
                        }
                    }
                };
                if (!_closing && !_aborting)
                {
                    this.Invoke(endAction);
                }
            }
            catch (Exception) { }
            finally { countDown.Signal(); }
        }
Пример #19
0
        private void StartResetSusClientID()
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Properties.Settings.Default.Language);

            Credentials cred = Credentials.GetInstance();

            if (dtGrdVResult.SelectedRows.Count != 0)
            {
                if (cred.InitializeCredential() == false)
                {
                    return;
                }
            }
            Logger.Write(lblCredentials);

            Action startAction = () => { lblCredentials.Text = cred.CredentialNotice; };

            if (!_closing)
            {
                this.Invoke(startAction);
            }

            System.Threading.CountdownEvent countEvent = new System.Threading.CountdownEvent(1);

            foreach (DataGridViewRow row in dtGrdVResult.SelectedRows)
            {
                countEvent.AddCount();
                ASyncClientParameters parameters = new ASyncClientParameters();
                parameters.RowIndex   = row.Index;
                parameters.Login      = cred.Login;
                parameters.Password   = cred.Password;
                parameters.CountEvent = countEvent;

                if (!_closing & !_aborting)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(ResetSusClientID, parameters);
                }
            }
            countEvent.Signal();
            countEvent.Wait(10000 * dtGrdVResult.SelectedRows.Count);

            if (!_closing && !_aborting)
            {
                SearchDuplicateWsusClientID();
            }

            Action endAction = () => { ChangeUIAccess(true); };

            if (!_closing)
            {
                this.Invoke(endAction);
            }
        }
Пример #20
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private <T extends org.neo4j.graphdb.PropertyContainer> Resource<T> test(System.Func<T> setup, String... queries) throws InterruptedException, java.util.concurrent.ExecutionException
        private Resource <T> Test <T>(System.Func <T> setup, params string[] queries) where T : Org.Neo4j.Graphdb.PropertyContainer
        {
            System.Threading.CountdownEvent resourceLocked     = new System.Threading.CountdownEvent(1);
            System.Threading.CountdownEvent listQueriesLatch   = new System.Threading.CountdownEvent(1);
            System.Threading.CountdownEvent finishQueriesLatch = new System.Threading.CountdownEvent(1);
            T resource;

            using (Transaction tx = _db.beginTx())
            {
                resource = setup();
                tx.Success();
            }
            _threads.execute(parameter =>
            {
                using (Transaction tx = _db.beginTx())
                {
                    tx.AcquireWriteLock(resource);
                    resourceLocked.Signal();
                    listQueriesLatch.await();
                }
                return(null);
            }, null);
            resourceLocked.await();

            _threads.executeAndAwait(parameter =>
            {
                try
                {
                    using (Transaction tx = _db.beginTx())
                    {
                        foreach (string query in queries)
                        {
                            _db.execute(query).close();
                        }
                        tx.Success();
                    }
                }
                catch (Exception t)
                {
                    Console.WriteLine(t.ToString());
                    Console.Write(t.StackTrace);
                    throw new Exception(t);
                }
                finally
                {
                    finishQueriesLatch.Signal();
                }
                return(null);
            }, null, waitingWhileIn(typeof(GraphDatabaseFacade), "execute"), SECONDS_TIMEOUT, SECONDS);

            return(new Resource <T>(listQueriesLatch, finishQueriesLatch, resource));
        }
Пример #21
0
        public void RealCall(Action <IRedisClient> callback)
        {
            //- 打开测试的 redis-server,请注意,每次调用都会清空数据。
#if REAL_REDIS
            cde.AddCount();
            using (var client = this.CreateClient())
            {
                client.FlushAll();
                callback(client);
            }
            cde.Signal();
#endif
        }
Пример #22
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private LockAcquisition acquireTwoLocksInAnotherThread(final boolean firstShared, final boolean secondShared, final java.util.concurrent.CountDownLatch firstLockFailed, final java.util.concurrent.CountDownLatch startSecondLock)
        private LockAcquisition AcquireTwoLocksInAnotherThread(bool firstShared, bool secondShared, System.Threading.CountdownEvent firstLockFailed, System.Threading.CountdownEvent startSecondLock)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockAcquisition lockAcquisition = new LockAcquisition();
            LockAcquisition lockAcquisition = new LockAcquisition();

            Future <Void> future = ThreadA.execute(state =>
            {
                using (Locks_Client client = NewLockClient(lockAcquisition))
                {
                    try
                    {
                        if (firstShared)
                        {
                            client.AcquireShared(_tracer, NODE, FIRST_NODE_ID);
                        }
                        else
                        {
                            client.AcquireExclusive(_tracer, NODE, FIRST_NODE_ID);
                        }
                        fail("Transaction termination expected");
                    }
                    catch (Exception e)
                    {
                        assertThat(e, instanceOf(typeof(LockClientStoppedException)));
                    }
                }

                lockAcquisition.Client = null;
                firstLockFailed.Signal();
                Await(startSecondLock);

                using (Locks_Client client = NewLockClient(lockAcquisition))
                {
                    if (secondShared)
                    {
                        client.AcquireShared(_tracer, NODE, FIRST_NODE_ID);
                    }
                    else
                    {
                        client.AcquireExclusive(_tracer, NODE, FIRST_NODE_ID);
                    }
                }
                return(null);
            });

            lockAcquisition.SetFuture(future, ThreadA.get());

            return(lockAcquisition);
        }
Пример #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 3000) public void conversationCanNotBeStoppedAndClosedConcurrently() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConversationCanNotBeStoppedAndClosedConcurrently()
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch answerLatch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent answerLatch = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch stopLatch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent stopLatch = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch stopReadyLatch = new java.util.concurrent.CountDownLatch(1);
            System.Threading.CountdownEvent stopReadyLatch = new System.Threading.CountdownEvent(1);
            const int sleepTime = 1000;

            doAnswer(invocation =>
            {
                stopReadyLatch.Signal();
                stopLatch.await();
                TimeUnit.MILLISECONDS.sleep(sleepTime);
                return(null);
            }).when(_client).stop();
            doAnswer(invocation =>
            {
                answerLatch.Signal();
                return(null);
            }).when(_client).close();

            ThreadingRule.execute(_conversation =>
            {
                _conversation.stop();
                return(null);
            }, _conversation);

            stopReadyLatch.await();
            ThreadingRule.execute(_conversation =>
            {
                _conversation.close();
                return(null);
            }, _conversation);

            long raceStartTime = DateTimeHelper.CurrentUnixTimeMillis();

            stopLatch.Signal();
            answerLatch.await();
            // execution time should be at least 1000 millis
            long executionTime = DateTimeHelper.CurrentUnixTimeMillis() - raceStartTime;

            assertTrue(string.Format("Execution time should be at least equal to {0:D}, but was {1:D}.", sleepTime, executionTime), executionTime >= sleepTime);
        }
Пример #24
0
 internal virtual void UpdatesDone()
 {
     UpdateTrackerCompletionLatch.Signal();
     try
     {
         UpdateTrackerCompletionLatch.await();
     }
     catch (InterruptedException e)
     {
         throw new Exception(e);
     }
     if (Barrier != null)
     {
         Barrier.reached();
     }
 }
Пример #25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 60_000) public void possibleToShutdownDbWhenItIsNotHealthyAndNotAllTransactionsAreApplied() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void PossibleToShutdownDbWhenItIsNotHealthyAndNotAllTransactionsAreApplied()
        {
            // adversary that makes page cache throw exception when node store is used
            ClassGuardedAdversary adversary = new ClassGuardedAdversary(new CountingAdversary(1, true), typeof(NodeStore));

            adversary.Disable();

            GraphDatabaseService db = AdversarialPageCacheGraphDatabaseFactory.create(_fs, adversary).newEmbeddedDatabaseBuilder(_testDir.databaseDir()).newGraphDatabase();

            System.Threading.CountdownEvent txStartLatch  = new System.Threading.CountdownEvent(1);
            System.Threading.CountdownEvent txCommitLatch = new System.Threading.CountdownEvent(1);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> result = java.util.concurrent.ForkJoinPool.commonPool().submit(() ->
            Future <object> result = ForkJoinPool.commonPool().submit(() =>
            {
                using (Transaction tx = Db.beginTx())
                {
                    txStartLatch.Signal();
                    Db.createNode();
                    Await(txCommitLatch);
                    tx.success();
                }
            });

            Await(txStartLatch);

            adversary.Enable();

            txCommitLatch.Signal();

            try
            {
                result.get();
                fail("Exception expected");
            }
            catch (ExecutionException ee)
            {
                // transaction is expected to fail because write through the page cache fails
                assertThat(ee.InnerException, instanceOf(typeof(TransactionFailureException)));
            }
            adversary.Disable();

            // shutdown should complete without any problems
            Db.shutdown();
        }
Пример #26
0
        private static long[] MergeAll(long[] output, LinkedList <int> bounds)
        {
            var buffer = new long[output.Count()];

            while (bounds.Count > 2)
            {
                var tmp_src = output;
                var tmp_buf = buffer;

                var w_node = bounds.First.Next;
                var w_copy = (bounds.Count - 1) % 2 == 1;
                int merges = (bounds.Count - 1) / 2;

                var counter = new System.Threading.CountdownEvent(merges);

                while (merges > 0)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(
                        w =>
                    {
                        MergeTwo(tmp_src, tmp_buf, (MergeWindow)w);
                        counter.Signal();
                    },
                        new MergeWindow(w_node)
                        );
                    var w_next = w_node.Next.Next;
                    bounds.Remove(w_node);
                    w_node = w_next;
                    merges--;
                }

                if (w_copy)
                {
                    var w_prev = w_node.Previous;
                    Array.Copy(tmp_src, w_prev.Value, tmp_buf, w_prev.Value, w_node.Value - w_prev.Value);
                }

                counter.Wait();

                output = tmp_buf;
                buffer = tmp_src;
            }

            return(output);
        }
Пример #27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void acquireExclusiveLockWhileHoldingSharedLockCanBeStopped() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void AcquireExclusiveLockWhileHoldingSharedLockCanBeStopped()
        {
            AcquiredLock thisThreadsSharedLock = AcquireSharedLockInThisThread();

            System.Threading.CountdownEvent sharedLockAcquired = new System.Threading.CountdownEvent(1);
            System.Threading.CountdownEvent startExclusiveLock = new System.Threading.CountdownEvent(1);
            LockAcquisition acquisition = AcquireSharedAndExclusiveLocksInAnotherThread(sharedLockAcquired, startExclusiveLock);

            Await(sharedLockAcquired);
            startExclusiveLock.Signal();
            AssertThreadIsWaitingForLock(acquisition);

            acquisition.Stop();
            AssertLockAcquisitionFailed(acquisition);

            thisThreadsSharedLock.Release();
            AssertNoLocksHeld();
        }
Пример #28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void acquireLockAfterOtherLockStoppedSameThread(boolean firstLockShared, boolean secondLockShared) throws Exception
        private void AcquireLockAfterOtherLockStoppedSameThread(bool firstLockShared, bool secondLockShared)
        {
            AcquiredLock thisThreadsExclusiveLock = AcquireExclusiveLockInThisThread();

            System.Threading.CountdownEvent firstLockFailed = new System.Threading.CountdownEvent(1);
            System.Threading.CountdownEvent startSecondLock = new System.Threading.CountdownEvent(1);

            LockAcquisition lockAcquisition = AcquireTwoLocksInAnotherThread(firstLockShared, secondLockShared, firstLockFailed, startSecondLock);

            AssertThreadIsWaitingForLock(lockAcquisition);

            lockAcquisition.Stop();
            Await(firstLockFailed);
            thisThreadsExclusiveLock.Release();
            startSecondLock.Signal();

            AssertLockAcquisitionSucceeded(lockAcquisition);
        }
Пример #29
0
        public async void Test1()
        {
            IBus  bus  = new Bus();
            IPort port = await bus.GetPort();

            var latch = new System.Threading.CountdownEvent(1);

            port.Subscribe <string>(s =>
            {
                if (string.Equals("Hello", s))
                {
                    latch.Signal();
                }
            });

            IPort pub = await bus.GetPort();

            pub.Publish("Hello");
            Assert.True(latch.Wait(1000));
        }
Пример #30
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private static java.util.concurrent.CountDownLatch loadThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool threadPool, int tasksToSubmit, final java.util.concurrent.CountDownLatch startLatch)
        private static System.Threading.CountdownEvent LoadThreadPool(QueuedThreadPool threadPool, int tasksToSubmit, System.Threading.CountdownEvent startLatch)
        {
            System.Threading.CountdownEvent endLatch = new System.Threading.CountdownEvent(1);
            for (int i = 0; i < tasksToSubmit; i++)
            {
                threadPool.execute(() =>
                {
                    startLatch.Signal();
                    try
                    {
                        endLatch.await();
                    }
                    catch (InterruptedException e)
                    {
                        Console.WriteLine(e.ToString());
                        Console.Write(e.StackTrace);
                    }
                });
            }
            return(endLatch);
        }
        public void TestRunTwoExperimentsSimultanouslyAndTerminateOneExperiment()
        {
            //assure workspace is empty
            AppContext.WorkspaceInstance.Clear();

            var done = new System.Threading.CountdownEvent(2);

            //start experiment one (takes more than 2 seconds to finish successfully)
            Experiment experimentOne = LoadExperiment("long-experiment.teml");
            MockProgress progressOne = new MockProgress();
            experimentOne.RunExperiment(progressOne, AppContext.WorkspaceInstance, AppContext.Components);
            experimentOne.ExperimentCompleted += (sender, args) =>
            {
                done.Signal();
            };

            //start experiment two and terminate it
            MockProgress progressTwo = new MockProgress();
            Experiment experimentTwo = LoadExperiment("infinite_loop_terminate_experiment_test.teml");
            experimentTwo.RunExperiment(progressTwo, AppContext.WorkspaceInstance, AppContext.Components);
            experimentTwo.ExperimentStarted += (sender, args) =>
            {
                experimentTwo.StopRunningExperiment();
            };
            experimentTwo.ExperimentCompleted += (sender, args) =>
            {
                done.Signal();
            };

            //wait for both experiment to end
            done.Wait(5000);

            //the experiment one should have ended successfully (it SHOULD NOT have been terminated)
            Assert.IsFalse(progressOne.HasError);
            Assert.AreEqual(Messages.ExperimentRunnerSuccessMessage, progressOne.CurrentStatus);

            //while exepriment two should be terminated
            Assert.IsTrue(progressTwo.HasError);
            Assert.AreEqual(Messages.ExperimentExecutionTerminated, progressTwo.CurrentStatus);
        }
            public static double[] ETCToPTC(double[][] Octave_ETC, double CutOffTime, int sample_frequency_in, int sample_frequency_out, double Rho_C)
            {
                int length = 4096;
                double[] IR = new double[(int)Math.Floor(sample_frequency_out * CutOffTime) + (int)length];
                double BW = (double)sample_frequency_out / (double)sample_frequency_in;

                //Convert to Pressure & Interpolate full resolution IR
                int ct = 0;
                System.Threading.Semaphore S = new System.Threading.Semaphore(0, 1);
                S.Release(1);

                double[] time = new double[(int)Math.Floor(sample_frequency_out * CutOffTime) + (int)length];
                double dt = 1f/(float)sample_frequency_out;
                for (int i = 0; i < time.Length; i++)
                {
                    time[i] = i * dt;
                }

                int proc = UI.PachydermAc_PlugIn.Instance.ProcessorSpec();
                double[][] output = new double[proc][];
                double[][] samplep = new double[proc][];
                System.Threading.Thread[] T = new System.Threading.Thread[proc];
                int[] to = new int[proc];
                int[] from = new int[proc];

                System.Threading.CountdownEvent CDE = new System.Threading.CountdownEvent(Octave_ETC[0].Length);

                for (int p = 0; p < proc; p++)
                {
                    output[p] = new double[length];
                    samplep[p] = new double[length * 2];
                    to[p] = p * Octave_ETC[0].Length / proc;
                    from[p] = (p + 1) * Octave_ETC[0].Length / proc;

                    T[p] = new System.Threading.Thread((thread) =>
                    {
                        int thr = (int)thread;
                        for (int t = to[thr]; t < from[thr]; t++)
                        {
                            ct++;
                            double[] pr = new double[8];
                            for (int oct = 0; oct < 8; oct++) pr[oct] = Math.Sqrt(Octave_ETC[oct][t] * Rho_C);

                            double sum = 0;
                            foreach (double d in pr) sum += d;
                            if (sum > 0)
                            {
                                output[thr] = Filter.Signal(pr, sample_frequency_out, 4096, thr);
                                //Audio.Pach_SP.Raised_Cosine_Window(ref output[thr]);
                                for (int k = 0; k < length; k++)
                                {
                                    IR[(int)Math.Floor(t * BW) + k] += output[thr][k];
                                }
                            }
                            CDE.Signal();
                        }
                    });
                    T[p].Start(p);
                }

                ProgressBox VB = new ProgressBox("Signal Production Progress");
                VB.Show();
                do
                {
                    if (CDE.IsSet)
                    {
                        break;
                    }
                    VB.Populate((int)(100 * (1f - ((float)CDE.CurrentCount / (float)IR.Length))));

                    System.Threading.Thread.Sleep(500);

                } while (true);

                //CDE.Wait();
                VB.Close();
                return IR;
            }