private static string GetMessage(SchemaObjectBase originalData, Executors.AUOperationType auOperationType)
		{
			if (originalData == null)
				throw new ArgumentNullException("originalData");

			return string.Format("ID:为 {0} 的对象的状态不允许执行{1}操作。", originalData.ID, auOperationType.ToString());
		}
示例#2
0
        public virtual void Run()
        {
            // Configure the client.
            DatagramChannelFactory f = new NioDatagramChannelFactory(Executors.NewCachedThreadPool
                                                                         (), workerCount);

            server = new ConnectionlessBootstrap(f);
            server.SetPipeline(Channels.Pipeline(RpcUtil.StageRpcMessageParser, rpcProgram, RpcUtil
                                                 .StageRpcUdpResponse));
            server.SetOption("broadcast", "false");
            server.SetOption("sendBufferSize", SendBufferSize);
            server.SetOption("receiveBufferSize", ReceiveBufferSize);
            // Listen to the UDP port
            ch = server.Bind(new IPEndPoint(port));
            IPEndPoint socketAddr = (IPEndPoint)ch.GetLocalAddress();

            boundPort = socketAddr.Port;
            Log.Info("Started listening to UDP requests at port " + boundPort + " for " + rpcProgram
                     + " with workerCount " + workerCount);
        }
示例#3
0
        /// <exception cref="System.Exception"/>
        public virtual void TestMultiThreadedCompressorPool()
        {
            int             iterations             = 4;
            ExecutorService threadpool             = Executors.NewFixedThreadPool(3);
            LinkedBlockingDeque <Compressor> queue = new LinkedBlockingDeque <Compressor>(2 * iterations
                                                                                          );
            Callable <bool> consumer = new _Callable_110(queue);
            Callable <bool> producer = new _Callable_119(this, queue);

            for (int i = 0; i < iterations; i++)
            {
                threadpool.Submit(consumer);
                threadpool.Submit(producer);
            }
            // wait for completion
            threadpool.Shutdown();
            threadpool.AwaitTermination(1000, TimeUnit.Seconds);
            Assert.Equal(LeaseCountErr, 0, CodecPool.GetLeasedCompressorsCount
                             (codec));
        }
        private static void TryStatementListenerAddRemove(
            RegressionEnvironment env,
            int numThreads,
            EPStatement statement,
            bool isEPL,
            int numRepeats)
        {
            var threadPool = Executors.NewFixedThreadPool(
                numThreads,
                new SupportThreadFactory(typeof(MultithreadStmtListenerAddRemove)).ThreadFactory);
            var future = new IFuture<object>[numThreads];
            for (var i = 0; i < numThreads; i++) {
                var callable = new StmtListenerAddRemoveCallable(env.Runtime, statement, isEPL, numRepeats);
                future[i] = threadPool.Submit(callable);
            }

            threadPool.Shutdown();
            SupportCompileDeployUtil.ExecutorAwait(threadPool, 10, TimeUnit.SECONDS);
            SupportCompileDeployUtil.AssertFutures(future);
        }
示例#5
0
        static BatchingProgressMonitor()
        {
            // To support garbage collection, start our thread but
            // swap out the thread factory. When our class is GC'd
            // the alarmQueueKiller will finalize and ask the executor
            // to shutdown, ending the worker.
            //
            int threads = 1;

            alarmQueue = new ScheduledThreadPoolExecutor(threads, new _ThreadFactory_66());
            alarmQueue.SetContinueExistingPeriodicTasksAfterShutdownPolicy(false);
            alarmQueue.SetExecuteExistingDelayedTasksAfterShutdownPolicy(false);
            alarmQueue.PrestartAllCoreThreads();
            // Now that the threads are running, its critical to swap out
            // our own thread factory for one that isn't in the ClassLoader.
            // This allows the class to GC.
            //
            alarmQueue.SetThreadFactory(Executors.DefaultThreadFactory());
            alarmQueueKiller = new _object_87();
        }
        private void TryIterate(EPServiceProvider epService, int numThreads, int numRepeats)
        {
            var threadPool = Executors.NewFixedThreadPool(numThreads);
            var future     = new Future <bool> [numThreads];

            for (int i = 0; i < numThreads; i++)
            {
                var callable = new StmtNamedWindowQueryCallable(Convert.ToString(i), epService, numRepeats);
                future[i] = threadPool.Submit(callable);
            }

            threadPool.Shutdown();
            threadPool.AwaitTermination(10, TimeUnit.SECONDS);

            Thread.Sleep(100);
            for (int i = 0; i < numThreads; i++)
            {
                Assert.IsTrue(future[i].GetValue(10, TimeUnit.SECONDS));
            }
        }
示例#7
0
 public LogAggregationService(Dispatcher dispatcher, Context context, DeletionService
                              deletionService, LocalDirsHandlerService dirsHandler)
     : base(typeof(Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Logaggregation.LogAggregationService
                   ).FullName)
 {
     /*
      * Expected deployment TLD will be 1777, owner=<NMOwner>, group=<NMGroup -
      * Group to which NMOwner belongs> App dirs will be created as 770,
      * owner=<AppOwner>, group=<NMGroup>: so that the owner and <NMOwner> can
      * access / modify the files.
      * <NMGroup> should obviously be a limited access group.
      */
     this.dispatcher        = dispatcher;
     this.context           = context;
     this.deletionService   = deletionService;
     this.dirsHandler       = dirsHandler;
     this.appLogAggregators = new ConcurrentHashMap <ApplicationId, AppLogAggregator>();
     this.threadPool        = Executors.NewCachedThreadPool(new ThreadFactoryBuilder().SetNameFormat
                                                                ("LogAggregationService #%d").Build());
 }
        public IAsyncTask Start()
        {
            if (this.IsDone)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("The task has been done!");
                }

                return(this);
            }

            if (Interlocked.CompareExchange(ref this.running, 1, 0) == 1)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("The task is running!");
                }

                return(this);
            }

            try
            {
                if (this.preCallbackOnMainThread != null)
                {
                    Executors.RunOnMainThread(this.preCallbackOnMainThread, true);
                }
            }
            catch (Exception e)
            {
                if (log.IsWarnEnabled)
                {
                    log.WarnFormat("{0}", e);
                }
            }

            Executors.RunAsync(this.action);

            return(this);
        }
示例#9
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
             if (Class != null)
             hashCode = hashCode * 59 + Class.GetHashCode();
             if (DisplayName != null)
             hashCode = hashCode * 59 + DisplayName.GetHashCode();
             if (Executors != null)
             hashCode = hashCode * 59 + Executors.GetHashCode();
             if (Icon != null)
             hashCode = hashCode * 59 + Icon.GetHashCode();
             if (IconClassName != null)
             hashCode = hashCode * 59 + IconClassName.GetHashCode();
             
             hashCode = hashCode * 59 + Idle.GetHashCode();
             
             hashCode = hashCode * 59 + JnlpAgent.GetHashCode();
             
             hashCode = hashCode * 59 + LaunchSupported.GetHashCode();
             if (LoadStatistics != null)
             hashCode = hashCode * 59 + LoadStatistics.GetHashCode();
             
             hashCode = hashCode * 59 + ManualLaunchAllowed.GetHashCode();
             if (MonitorData != null)
             hashCode = hashCode * 59 + MonitorData.GetHashCode();
             
             hashCode = hashCode * 59 + NumExecutors.GetHashCode();
             
             hashCode = hashCode * 59 + Offline.GetHashCode();
             if (OfflineCause != null)
             hashCode = hashCode * 59 + OfflineCause.GetHashCode();
             if (OfflineCauseReason != null)
             hashCode = hashCode * 59 + OfflineCauseReason.GetHashCode();
             
             hashCode = hashCode * 59 + TemporarilyOffline.GetHashCode();
         return hashCode;
     }
 }
示例#10
0
        public virtual void ConcurrentPackRefs_onlyOneWritesPackedRefs()
        {
            RevBlob a = tr.Blob("a");

            tr.LightweightTag("t", a);
            CyclicBarrier   syncPoint = new CyclicBarrier(2);
            Callable <int>  packRefs  = new _Callable_131(this, syncPoint);
            ExecutorService pool      = Executors.NewFixedThreadPool(2);

            try
            {
                Future <int> p1 = pool.Submit(packRefs);
                Future <int> p2 = pool.Submit(packRefs);
                NUnit.Framework.Assert.AreEqual(1, p1.Get() + p2.Get());
            }
            finally
            {
                pool.Shutdown();
                pool.AwaitTermination(long.MaxValue, TimeUnit.SECONDS);
            }
        }
示例#11
0
        /// <exception cref="System.Exception"/>
        internal static long PerformanceTest(int arrayLength, int maxArrays, int nThreads
                                             , int[] sleepTimeMSs, ByteArrayManager impl)
        {
            ExecutorService        pool    = Executors.NewFixedThreadPool(nThreads);
            IList <Future <Void> > futures = new AList <Future <Void> >(sleepTimeMSs.Length);
            long startTime = Time.MonotonicNow();

            for (int i = 0; i < sleepTimeMSs.Length; i++)
            {
                long sleepTime = sleepTimeMSs[i];
                futures.AddItem(pool.Submit(new _Callable_628(impl, arrayLength, sleepTime)));
            }
            foreach (Future <Void> f in futures)
            {
                f.Get();
            }
            long endTime = Time.MonotonicNow();

            pool.Shutdown();
            return(endTime - startTime);
        }
示例#12
0
        public virtual IProgressResult <float, Dictionary <string, Object> > LoadAssetsToMapAsync(System.Type type, params string[] paths)
        {
            try
            {
                if (paths == null || paths.Length <= 0)
                {
                    throw new System.ArgumentNullException("paths", "The paths is null or empty!");
                }

                if (type == null)
                {
                    throw new System.ArgumentNullException("type");
                }

                return(Executors.RunOnCoroutine <float, Dictionary <string, Object> >((promise) => DoLoadAssetsToMapAsync(promise, type, paths)));
            }
            catch (System.Exception e)
            {
                return(new ImmutableProgressResult <float, Dictionary <string, Object> >(e, 0f));
            }
        }
示例#13
0
        private static void TryIterate(
            RegressionEnvironment env,
            RegressionPath path,
            int numThreads,
            int numRepeats)
        {
            var threadPool = Executors.NewFixedThreadPool(
                numThreads,
                new SupportThreadFactory(typeof(MultithreadStmtNamedWindowFAF)).ThreadFactory);
            var future = new IFuture<object>[numThreads];
            for (var i = 0; i < numThreads; i++) {
                var callable = new StmtNamedWindowQueryCallable(env, path, numRepeats, Convert.ToString(i));
                future[i] = threadPool.Submit(callable);
            }

            threadPool.Shutdown();
            SupportCompileDeployUtil.ExecutorAwait(threadPool, 10, TimeUnit.SECONDS);

            SupportCompileDeployUtil.ThreadSleep(100);
            SupportCompileDeployUtil.AssertFutures(future);
        }
示例#14
0
        IAsyncResult <int> Calculate()
        {
            return(Executors.RunAsync <int>(() =>
            {
                Debug.LogFormat("Calculate Task ThreadId:{0}", Thread.CurrentThread.ManagedThreadId);
                int total = 0;
                for (int i = 0; i < 20; i++)
                {
                    total += i;
                    try
                    {
                        Thread.Sleep(100);
                    }
                    catch (Exception)
                    {
                    }
                }

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

            try
            {
                UniqueElementsConsumer consumer = new UniqueElementsConsumer();

                // when
                // producer thread
                System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> produce = executor.submit(stressUntil(latch, buffer::produce));
                Future <object> produce = executor.submit(StressUntil(latch, buffer.produce));

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

                // then without illegal transitions or exceptions
                consume.get();
                latch.Signal();
                produce.get();
            }
            finally
            {
                executor.shutdown();
            }
            assertEquals(0, buffer.NumSilentQueryDrops());
        }
示例#16
0
        private void TryListener(int numThreads, int numRoutes)
        {
            EPStatement stmtTrigger = _engine.EPAdministrator.CreateEPL(
                " select * from " + typeof(SupportBean).FullName);

            EPStatement stmtListen = _engine.EPAdministrator.CreateEPL(
                " select * from " + typeof(SupportMarketDataBean).FullName);
            SupportMTUpdateListener listener = new SupportMTUpdateListener();

            stmtListen.Events += listener.Update;

            // Set of events routed by each listener
            ICollection <SupportMarketDataBean> routed = new HashSet <SupportMarketDataBean>().AsSyncCollection();

            var threadPool = Executors.NewFixedThreadPool(numThreads);
            var future     = new Future <bool> [numThreads];

            for (int i = 0; i < numThreads; i++)
            {
                var callable = new StmtListenerCreateStmtCallable(i, _engine, stmtTrigger, numRoutes, routed);
                future[i] = threadPool.Submit(callable);
            }

            threadPool.Shutdown();
            threadPool.AwaitTermination(TimeSpan.FromSeconds(10));

            for (int i = 0; i < numThreads; i++)
            {
                Assert.IsTrue(future[i].GetValueOrDefault());
            }

            // assert
            EventBean[] results = listener.GetNewDataListFlattened();
            Assert.IsTrue(results.Length >= numThreads * numRoutes);

            foreach (var found in routed.Select(routedEvent => results.Any(eventBean => eventBean.Underlying == routedEvent)))
            {
                Assert.IsTrue(found);
            }
        }
        private void TrySend(int numThreads, int numRepeats)
        {
            var threadPool = Executors.NewFixedThreadPool(numThreads);
            var future     = new Future <IList <string> > [numThreads];

            for (int i = 0; i < numThreads; i++)
            {
                var callable = new StmtNamedWindowDeleteCallable(Convert.ToString(i), _engine, numRepeats);
                future[i] = threadPool.Submit(callable);
            }

            threadPool.Shutdown();
            threadPool.AwaitTermination(TimeSpan.FromSeconds(10));

            // Compute list of expected
            List <String> expectedIdsList = new List <String>();

            for (int i = 0; i < numThreads; i++)
            {
                expectedIdsList.AddAll(future[i].GetValueOrDefault());
            }
            String[] expectedIds = expectedIdsList.ToArray();

            Assert.AreEqual(2 * numThreads * numRepeats, _listenerWindow.GetNewDataList().Count);   // old and new each
            Assert.AreEqual(2 * numThreads * numRepeats, _listenerConsumer.GetNewDataList().Count); // old and new each

            // Compute list of received
            EventBean[] newEvents   = _listenerWindow.GetNewDataListFlattened();
            String[]    receivedIds = new String[newEvents.Length];
            for (int i = 0; i < newEvents.Length; i++)
            {
                receivedIds[i] = (String)newEvents[i].Get("TheString");
            }
            Assert.AreEqual(receivedIds.Length, expectedIds.Length);

            Array.Sort(receivedIds);
            Array.Sort(expectedIds);

            CompatExtensions.DeepEquals(expectedIds, receivedIds);
        }
示例#18
0
        private static void TrySend(
            RegressionEnvironment env,
            int numThreads,
            int numRepeats)
        {
            env.CompileDeploy(
                "@Name('s0') select (select Id from SupportBean_S0#length(1000000) where Id = S1.Id) as value from SupportBean_S1 as S1");
            var listener = new SupportMTUpdateListener();
            env.Statement("s0").AddListener(listener);

            var threadPool = Executors.NewFixedThreadPool(
                numThreads,
                new SupportThreadFactory(typeof(MultithreadStmtSubquery)).ThreadFactory);
            var future = new IFuture<object>[numThreads];
            for (var i = 0; i < numThreads; i++) {
                var callable = new StmtSubqueryCallable(i, env.Runtime, numRepeats);
                future[i] = threadPool.Submit(callable);
            }

            threadPool.Shutdown();
            SupportCompileDeployUtil.ExecutorAwait(threadPool, 10, TimeUnit.SECONDS);
            SupportCompileDeployUtil.AssertFutures(future);

            // Assert results
            var totalExpected = numThreads * numRepeats;

            // assert new data
            var resultNewData = listener.GetNewDataListFlattened();
            Assert.AreEqual(totalExpected, resultNewData.Length);

            ISet<int> values = new HashSet<int>();
            foreach (var theEvent in resultNewData) {
                values.Add(theEvent.Get("value").AsInt32());
            }

            Assert.AreEqual(totalExpected, values.Count, "Unexpected duplicates");

            listener.Reset();
            env.UndeployAll();
        }
示例#19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void consume(String name, org.neo4j.unsafe.impl.batchimport.InputIterator entities, org.neo4j.unsafe.impl.batchimport.input.csv.Header header, Deserializer deserializer) throws java.io.IOException
        private void Consume(string name, InputIterator entities, Header header, Deserializer deserializer)
        {
            using (PrintStream @out = File(name + "header.csv"))
            {
                Serialize(@out, header);
            }

            try
            {
                int             threads  = Runtime.Runtime.availableProcessors();
                ExecutorService executor = Executors.newFixedThreadPool(threads);
                for (int i = 0; i < threads; i++)
                {
                    int id = i;
                    executor.submit((Callable <Void>)() =>
                    {
                        StringDeserialization deserialization = new StringDeserialization(_config);
                        using (PrintStream @out = File(name + "-" + id + ".csv"), InputChunk chunk = entities.NewChunk())
                        {
                            InputEntity entity = new InputEntity();
                            while (entities.Next(chunk))
                            {
                                while (chunk.next(entity))
                                {
                                    @out.println(deserializer.Apply(entity, deserialization, header));
                                }
                            }
                        }
                        return(null);
                    });
                }
                executor.shutdown();
                executor.awaitTermination(10, TimeUnit.MINUTES);
            }
            catch (InterruptedException e)
            {
                Thread.CurrentThread.Interrupt();
                throw new IOException(e);
            }
        }
        private void TrySend(EPServiceProvider epService, SupportMTUpdateListener listenerWindow, SupportMTUpdateListener listenerConsumer, int numThreads, int numRepeats)
        {
            var threadPool = Executors.NewFixedThreadPool(numThreads);
            var future     = new Future <IList <string> > [numThreads];

            for (int i = 0; i < numThreads; i++)
            {
                var callable = new StmtNamedWindowDeleteCallable(Convert.ToString(i), epService, numRepeats);
                future[i] = threadPool.Submit(callable);
            }

            threadPool.Shutdown();
            threadPool.AwaitTermination(10, TimeUnit.SECONDS);

            // compute list of expected
            var expectedIdsList = new List <string>();

            for (int i = 0; i < numThreads; i++)
            {
                expectedIdsList.AddAll(future[i].GetValueOrDefault());
            }
            string[] expectedIds = expectedIdsList.ToArray();

            Assert.AreEqual(2 * numThreads * numRepeats, listenerWindow.NewDataList.Count);   // old and new each
            Assert.AreEqual(2 * numThreads * numRepeats, listenerConsumer.NewDataList.Count); // old and new each

            // compute list of received
            EventBean[] newEvents   = listenerWindow.GetNewDataListFlattened();
            var         receivedIds = new string[newEvents.Length];

            for (int i = 0; i < newEvents.Length; i++)
            {
                receivedIds[i] = (string)newEvents[i].Get("TheString");
            }
            Assert.AreEqual(receivedIds.Length, expectedIds.Length);

            Array.Sort(receivedIds);
            Array.Sort(expectedIds);
            CompatExtensions.DeepEquals(expectedIds, receivedIds);
        }
        public virtual void TestParallelThreadsWithDifferentLocales()
        {
            CyclicBarrier barrier = new CyclicBarrier(2);
            // wait for the other thread to set its locale
            ExecutorService pool = Executors.NewFixedThreadPool(2);

            try
            {
                Future <TranslationBundle> root = pool.Submit(new _T879158014(this, NLS.ROOT_LOCALE,
                                                                              barrier));
                Future <TranslationBundle> german = pool.Submit(new _T879158014(this, Sharpen.Extensions.GetGermanCulture(),
                                                                                barrier));
                NUnit.Framework.Assert.AreEqual(NLS.ROOT_LOCALE, root.Get().EffectiveLocale());
                NUnit.Framework.Assert.AreEqual(Sharpen.Extensions.GetGermanCulture(), german.Get
                                                    ().EffectiveLocale());
            }
            finally
            {
                pool.Shutdown();
                pool.AwaitTermination(long.MaxValue, TimeUnit.SECONDS);
            }
        }
  public int computeItemSimilarities(int degreeOfParallelism, int maxDurationInHours, SimilarItemsWriter writer)
    {

    ExecutorService executorService = Executors.newFixedThreadPool(degreeOfParallelism + 1);

    Output output = null;
    try {
      writer.open();

      DataModel dataModel = getRecommender().getDataModel();

      BlockingQueue<long[]> itemsIDsInBatches = queueItemIDsInBatches(dataModel, batchSize);
      BlockingQueue<List<SimilarItems>> results = new LinkedBlockingQueue<List<SimilarItems>>();

      AtomicInteger numActiveWorkers = new AtomicInteger(degreeOfParallelism);
      for (int n = 0; n < degreeOfParallelism; n++) {
        executorService.execute(new SimilarItemsWorker(n, itemsIDsInBatches, results, numActiveWorkers));
      }

      output = new Output(results, writer, numActiveWorkers);
      executorService.execute(output);

    } catch (Exception e) {
      throw new IOException(e);
    } finally {
      executorService.shutdown();
      try {
        bool succeeded = executorService.awaitTermination(maxDurationInHours, TimeUnit.HOURS);
        if (!succeeded) {
          throw new RuntimeException("Unable to complete the computation in " + maxDurationInHours + " hours!");
        }
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      Closeables.close(writer, false);
    }

    return output.getNumSimilaritiesProcessed();
  }
示例#23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test void takeOrAwaitLatchMustAwaitExistingLatchAndReturnNull() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        internal virtual void TakeOrAwaitLatchMustAwaitExistingLatchAndReturnNull()
        {
            AtomicReference <Thread> threadRef = new AtomicReference <Thread>();
            BinaryLatch latch = _latches.takeOrAwaitLatch(42);

            assertThat(latch, @is(notNullValue()));
            ExecutorService      executor = Executors.newSingleThreadExecutor();
            Future <BinaryLatch> future   = executor.submit(() =>
            {
                threadRef.set(Thread.CurrentThread);
                return(_latches.takeOrAwaitLatch(42));
            });
            Thread th;

            do
            {
                th = threadRef.get();
            } while (th == null);
            ThreadTestUtils.awaitThreadState(th, 10_000, Thread.State.WAITING);
            latch.Release();
            assertThat(future.get(1, TimeUnit.SECONDS), @is(nullValue()));
        }
示例#24
0
        private void TrySend(
            RegressionEnvironment env,
            int numThreads,
            int numRepeats,
            int numStmts,
            SupportCountListener[] listeners)
        {
            var executor = Executors.NewFixedThreadPool(
                numThreads,
                new SupportThreadFactory(typeof(MultithreadViewTimeWindow)).ThreadFactory);
            var future = new IFuture<bool>[numThreads];
            for (var i = 0; i < numThreads; i++) {
                var callable = new SendEventCallable(i, env.Runtime, new GeneratorEnumerator(numRepeats));
                future[i] = executor.Submit(callable);
            }

            log.Info("Waiting for threadpool shutdown");
            executor.Shutdown();
            executor.AwaitTermination(TimeSpan.FromSeconds(30));

            for (var i = 0; i < numThreads; i++) {
                Assert.IsTrue(future[i].GetValue(TimeSpan.FromSeconds(5)));
            }

            // set time to a large value
            log.Info("Waiting for calm down");
            Thread.Sleep(5000);

            // Assert results
            var totalExpected = numThreads * numRepeats;

            // assert new data
            for (var i = 0; i < numStmts; i++) {
                var count = listeners[i].CountNew;
                Assert.AreEqual(count, totalExpected);
                var countOld = listeners[i].CountNew;
                Assert.AreEqual(countOld, totalExpected);
            }
        }
        public static void Main(string[] args)
        {
            Properties options = StringUtils.ArgsToProperties(args, ArgOptionDefs());

            if (args.Length < 1 || options.Contains("help"))
            {
                log.Info(Usage());
                return;
            }
            Pattern posPattern          = options.Contains("searchPos") ? Pattern.Compile(options.GetProperty("searchPos")) : null;
            Pattern wordPattern         = options.Contains("searchWord") ? Pattern.Compile(options.GetProperty("searchWord")) : null;
            bool    plainPrint          = PropertiesUtils.GetBool(options, "plain", false);
            bool    ner                 = PropertiesUtils.GetBool(options, "ner", false);
            bool    detailedAnnotations = PropertiesUtils.GetBool(options, "detailedAnnotations", false);

            string[]     remainingArgs = options.GetProperty(string.Empty).Split(" ");
            IList <File> fileList      = new List <File>();

            foreach (string remainingArg in remainingArgs)
            {
                fileList.Add(new File(remainingArg));
            }
            SpanishXMLTreeReaderFactory trf  = new SpanishXMLTreeReaderFactory(true, true, ner, detailedAnnotations);
            IExecutorService            pool = Executors.NewFixedThreadPool(Runtime.GetRuntime().AvailableProcessors());

            foreach (File file in fileList)
            {
                pool.Execute(null);
            }
            pool.Shutdown();
            try
            {
                pool.AwaitTermination(long.MaxValue, TimeUnit.Nanoseconds);
            }
            catch (Exception e)
            {
                throw new RuntimeInterruptedException(e);
            }
        }
示例#26
0
        private static Object[] TryMT(Func <bool>[] callables)
        {
            var threadPool = Executors.NewFixedThreadPool(callables.Length);

            var futures = new Future <bool> [callables.Length];

            for (int i = 0; i < callables.Length; i++)
            {
                futures[i] = threadPool.Submit(callables[i]);
            }

            threadPool.Shutdown();
            threadPool.AwaitTermination(TimeSpan.FromSeconds(10));

            var results = new Object[futures.Length];

            for (int i = 0; i < futures.Length; i++)
            {
                results[i] = futures[i].GetValueOrDefault();
            }
            return(results);
        }
示例#27
0
        static InputManager()
        {
            if (!Application.isPlaying)
            {
                return;
            }
            var devices = new List <IInputDevice>()
            {
                new MobileInputDevice(),
                new StandardInputDevice(),
            };

            foreach (var inputDevice in devices)
            {
                if (inputDevice.CanUse())
                {
                    currentDevice = inputDevice;
                    break;
                }
            }
            Executors.RunOnCoroutineNoReturn(Update());
        }
        public JsonResult Create([Bind(Include = "ExecutorID,UserID,ProjectID")] Executors executors)
        {
            var res = true;

            if (ModelState.IsValid)
            {
                db.Executors.Add(executors);
                int result = db.SaveChanges();
                if (result != 1)
                {
                    res = false;
                }
            }

            /*ViewBag.UserID = new SelectList(db.Users, "UserID", "FirstName", executors.UserID);
             * ViewBag.ProjectID = new SelectList(db.Projects, "ProjectID", "Name", executors.ProjectID);
             * return View(executors);*/
            return(Json(new
            {
                result = res, id = executors.ExecutorID
            }, JsonRequestBehavior.AllowGet));
        }
示例#29
0
        private static void TrySend(
            RegressionEnvironment env,
            int numThreads,
            int numEventsPerThread)
        {
            // setup statements
            var path = new RegressionPath();
            env.CompileDeploy("create window MyWindow#keepall as select * from SupportBean", path);
            env.CompileDeploy(
                "on SupportBean sb " +
                "merge MyWindow nw where nw.TheString = sb.TheString " +
                " when not matched then insert select * " +
                " when matched then update set IntPrimitive = nw.IntPrimitive + 1",
                path);

            // execute
            var threadPool = Executors.NewFixedThreadPool(
                numThreads,
                new SupportThreadFactory(typeof(MultithreadStmtNamedWindowMerge)).ThreadFactory);
            var future = new IFuture<bool?>[numThreads];
            for (var i = 0; i < numThreads; i++) {
                future[i] = threadPool.Submit(new StmtNamedWindowMergeCallable(env.Runtime, numEventsPerThread));
            }

            threadPool.Shutdown();
            SupportCompileDeployUtil.ExecutorAwait(threadPool, 10, TimeUnit.SECONDS);
            SupportCompileDeployUtil.AssertFutures(future);

            // compare
            var rows = env.CompileExecuteFAF("select * from MyWindow", path).Array;
            Assert.AreEqual(numEventsPerThread, rows.Length);
            foreach (var row in rows) {
                Assert.AreEqual(numThreads - 1, row.Get("IntPrimitive"));
            }

            //long deltaTime = endTime - startTime;
            //System.out.println("Totals updated: " + totalUpdates + "  Delta cumu: " + deltaCumulative + "  Delta pooled: " + deltaTime);
            env.UndeployAll();
        }
示例#30
0
        public void TestJoin()
        {
            var es        = Executors.NewFixedThreadPool(10);
            var runnables = new List <MyRunnable>();

            for (int i = 0; i < 6; i++)
            {
                runnables.Add(new MyRunnable(_service.EPRuntime));
            }

            foreach (var toRun in runnables)
            {
                es.Submit(toRun.Run);
            }
            es.Shutdown();
            es.AwaitTermination(TimeSpan.FromSeconds(20));

            foreach (MyRunnable runnable in runnables)
            {
                Assert.IsNull(runnable.Exception);
            }
        }
        public void Shutdown()
        {
            ScheduledThreadPoolExecutor e = new ScheduledThreadPoolExecutor(5, Executors.DefaultThreadFactory());
            bool run = false;

            e.Schedule(new RunnableAction(delegate {
                run = true;
            }), 100, TimeUnit.MILLISECONDS);

            Thread.Sleep(50);

            e.Shutdown();
            Assert.IsTrue(e.IsShutdown());
            Assert.IsFalse(e.IsTerminated(), "Terminated");
            Assert.IsTrue(e.IsTerminating(), "Terminating");

            Thread.Sleep(100);

            Assert.IsTrue(run, "Not run");
            Assert.IsTrue(e.IsTerminated(), "Terminated");
            Assert.IsFalse(e.IsTerminating(), "Terminating");
        }
		public void BeforeExecute(Executors.AUOperationType operationType)
		{
			switch (operationType)
			{
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.None:
					break;
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.AddAdminSchema:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.RemoveAdminSchema:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.UpdateAdminSchema:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.AddAdminUnit:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.RemoveAdminUnit:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.UpdateAdminUnit:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.AddSchemaRole:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.RemoveSchemaRole:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.UpdateAdminSchemaRole:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.ModifyAURoleMembers:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.AddAUScopeItem:
				case MCS.Library.SOA.DataObjects.Security.AUObjects.Executors.AUOperationType.RemoveAUScopeItem:
				default:
					AUCacheHelper.InvalidateAllCache();
					break;
			}
		}
 public override async Task CompleteProcessingMessageAsync(BrokeredMessage message, Executors.FunctionResult result, CancellationToken cancellationToken)
 {
     _trace.Info("Custom processor End called!");
     await base.CompleteProcessingMessageAsync(message, result, cancellationToken);
 }
		public void BeforeExecute(Executors.AUOperationType operationType)
		{
			AUOperationSnapshot snapshot = new AUOperationSnapshot() { OperationType = operationType };

			AUOperationSnapshotAdapter.Instance.Update(snapshot);
		}
		public void AfterExecute(Executors.AUOperationType operationType)
		{
		}
		public AUStatusCheckException(SchemaObjectBase originalData, Executors.AUOperationType auOperationType)
			: base(GetMessage(originalData, auOperationType))
		{
			this.originalData = originalData;
			this.auOperationType = auOperationType;
		}