Beispiel #1
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: public void generateEvent(final org.neo4j.graphdb.event.ErrorState error, final Throwable cause)
        public virtual void GenerateEvent(ErrorState error, Exception cause)
        {
            ExecutorService executor = Executors.newSingleThreadExecutor();

            executor.execute(() => _kernelEventHandlers.kernelPanic(error, cause));
            executor.shutdown();
        }
Beispiel #2
0
 /// <seealso cref= InvokeFuture#tryAsyncExecuteInvokeCallbackAbnormally() </seealso>
 public virtual void tryAsyncExecuteInvokeCallbackAbnormally()
 {
     try
     {
         Protocol protocol = ProtocolManager.getProtocol(Remoting.ProtocolCode.fromBytes(this.protocol));
         if (null != protocol)
         {
             CommandHandler commandHandler = protocol.CommandHandler;
             if (null != commandHandler)
             {
                 ExecutorService executor = commandHandler.DefaultExecutor;
                 if (null != executor)
                 {
                     executor.execute(new TempRunnable(this));
                 }
             }
             else
             {
                 logger.LogError("Executor null in commandHandler of protocolCode [{}].", this.protocol);
             }
         }
         else
         {
             logger.LogError("protocolCode [{}] not registered!", this.protocol);
         }
     }
     catch (System.Exception e)
     {
         logger.LogError("Exception caught when executing invoke callback abnormally.", e);
     }
 }
Beispiel #3
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);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Executes an audio track with the given player and volume. </summary>
        /// <param name="listener"> A listener for track state events </param>
        /// <param name="track"> The audio track to execute </param>
        /// <param name="configuration"> The audio configuration to use for executing </param>
        /// <param name="volumeLevel"> The mutable volume level to use </param>
        //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
        //ORIGINAL LINE: public void executeTrack(final TrackStateListener listener, InternalAudioTrack track, AudioConfiguration configuration, AtomicInteger volumeLevel)
        public virtual void executeTrack(TrackStateListener listener, InternalAudioTrack track, AudioConfiguration configuration, AtomicInteger volumeLevel)
        {
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final AudioTrackExecutor executor = createExecutorForTrack(track, configuration, volumeLevel);
            AudioTrackExecutor executor = createExecutorForTrack(track, configuration, volumeLevel);

            track.assignExecutor(executor, true);

            trackPlaybackExecutorService.execute(() => executor.execute(listener));
        }
 /// <summary>
 /// Process event.
 /// </summary>
 /// <param name="runnable"> Runnable </param>
 public virtual void onEvent(Runnable runnable)
 {
     try
     {
         executor.execute(runnable);
     }
     catch (java.lang.Exception t)
     {
         logger.LogError("Exception caught when execute connection event!", t);
     }
 }
Beispiel #6
0
 public override void Execute(ThreadStart command)
 {
     if (_executor != null)
     {
         _executor.execute(command);
     }
     else
     {
         command.run();
     }
 }
Beispiel #7
0
        /// <summary>
        /// Process the remoting command with its own executor or with the defaultExecutor if its own if null.
        /// </summary>
        /// <param name="ctx"> RemotingContext </param>
        /// <param name="msg"> T </param>
        /// <param name="defaultExecutor"> ExecutorService, default executor </param>
        public virtual void process(RemotingContext ctx, RemotingCommand msg, ExecutorService defaultExecutor)
        {
            ProcessTask task = new ProcessTask(this, ctx, msg);

            if (Executor != null)
            {
                Executor.execute(task);
            }
            else
            {
                defaultExecutor.execute(task);
            }
        }
  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();
  }
Beispiel #9
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void restartWhileDoingTransactions() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void RestartWhileDoingTransactions()
        {
            // given
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: org.neo4j.causalclustering.discovery.Cluster<?> cluster = clusterRule.startCluster();
            Cluster <object> cluster = ClusterRule.startCluster();

            // when
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.graphdb.GraphDatabaseService coreDB = cluster.getCoreMemberById(0).database();
            GraphDatabaseService coreDB = cluster.GetCoreMemberById(0).database();

            ExecutorService executor = Executors.newCachedThreadPool();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicBoolean done = new java.util.concurrent.atomic.AtomicBoolean(false);
            AtomicBoolean done = new AtomicBoolean(false);

            executor.execute(() =>
            {
                while (!done.get())
                {
                    try
                    {
                        using (Transaction tx = coreDB.BeginTx())
                        {
                            Node node = coreDB.CreateNode(label("boo"));
                            node.setProperty("foobar", "baz_bat");
                            tx.success();
                        }
                    }
                    catch (Exception e) when(e is AcquireLockTimeoutException || e is WriteOperationsNotAllowedException)
                    {
                        // expected sometimes
                    }
                }
            });
            Thread.Sleep(500);

            cluster.RemoveCoreMemberWithServerId(1);
            cluster.AddCoreMemberWithId(1).start();
            Thread.Sleep(500);

            // then
            done.set(true);
            executor.shutdown();
        }
Beispiel #10
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void runWorkers(java.util.concurrent.ExecutorService executorService) throws InterruptedException
        private void runWorkers(ExecutorService executorService)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int numberOfIterations = configuration.getNumberOfIterations();
            int numberOfIterations = configuration.NumberOfIterations;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int taskCount = numberOfIterations * configuration.getWorkerTasks().length;
            int taskCount = numberOfIterations * configuration.WorkerTasks.Length;

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.CountDownLatch sync = new java.util.concurrent.CountDownLatch(taskCount);
            System.Threading.CountdownEvent sync = new System.Threading.CountdownEvent(taskCount);

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.Timer timer = new java.util.Timer();
            Timer timer = new Timer();

            timer.scheduleAtFixedRate(new ProgressReporter(taskCount, sync, configuration.Color), 2000, 2000);

            Console.WriteLine("Generating load. Total tasks: " + taskCount + "... ");

            for (int i = 1; i <= numberOfIterations; i++)
            {
                foreach (ThreadStart runnable in configuration.WorkerTasks)
                {
                    executorService.execute(wrap(runnable, sync));
                }
            }

            sync.await();

            timer.cancel();

            if (configuration.Color)
            {
                Console.Write(CLEAR_LINE + ANSI_GREEN);
            }
            Console.WriteLine("Finished generating load.");
            if (configuration.Color)
            {
                Console.Write(ANSI_RESET);
            }

            executorService.shutdown();
        }
Beispiel #11
0
        /*
         * In case if writer thread can't grab write lock now, it should be added to
         * into a waiting list, wait till resource will be free and grab it.
         */
//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 testWaitingWriterLock() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void TestWaitingWriterLock()
        {
            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);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockTransaction lockTransaction = new LockTransaction();
            LockTransaction lockTransaction = new LockTransaction();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final LockTransaction anotherTransaction = new LockTransaction();
            LockTransaction anotherTransaction = new LockTransaction();

            @lock.Mark();
            @lock.AcquireReadLock(LockTracer.NONE, lockTransaction);
            @lock.Mark();
            @lock.AcquireReadLock(LockTracer.NONE, anotherTransaction);

//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 writer = CreateWriter(@lock, lockTransaction, writerCompletedLatch);

            // start writer that will be placed in a wait list
            _executor.execute(writer);

            // wait till writer will be added into a list of waiters
            WaitWaitingThreads(@lock, 1);

            assertEquals("No writers for now.", 0, @lock.WriteCount);
            assertEquals(2, @lock.ReadCount);

            // releasing read locks that will allow writer to grab the lock
            @lock.ReleaseReadLock(lockTransaction);
            @lock.ReleaseReadLock(anotherTransaction);

            // wait till writer will have write lock
            writerCompletedLatch.await();

            assertEquals(1, @lock.WriteCount);
            assertEquals(0, @lock.ReadCount);

            // now releasing write lock
            @lock.ReleaseWriteLock(lockTransaction);

            assertEquals("Lock should not have any writers left.", 0, @lock.WriteCount);
            assertEquals("No waiting threads left.", 0, @lock.WaitingThreadsCount);
            assertEquals("No lock elements left.", 0, @lock.TxLockElementCount);
        }
Beispiel #12
0
        public virtual void TestConcurrentHashMap()
        {
            // don't make threadCount and keyCount random, otherwise easily OOMs or fails otherwise:
            const int       threadCount = 8, keyCount = 1024;
            ExecutorService exec               = Executors.newFixedThreadPool(threadCount, new NamedThreadFactory("testConcurrentHashMap"));
            WeakIdentityMap <object, int?> map = WeakIdentityMap <object, int?> .NewConcurrentHashMap(Random().NextBoolean());

            // we keep strong references to the keys,
            // so WeakIdentityMap will not forget about them:
            AtomicReferenceArray <object> keys = new AtomicReferenceArray <object>(keyCount);

            for (int j = 0; j < keyCount; j++)
            {
                keys.Set(j, new object());
            }

            try
            {
                for (int t = 0; t < threadCount; t++)
                {
                    Random rnd = new Random(Random().Next());
                    exec.execute(new RunnableAnonymousInnerClassHelper(this, keyCount, map, keys, rnd));
                }
            }
            finally
            {
                exec.shutdown();
                while (!exec.awaitTermination(1000L, TimeUnit.MILLISECONDS))
                {
                    ;
                }
            }

            // clear strong refs
            for (int j = 0; j < keyCount; j++)
            {
                keys.Set(j, null);
            }

            // check that GC does not cause problems in reap() method:
            int size = map.Size();

            for (int i = 0; size > 0 && i < 10; i++)
            {
                try
                {
                    System.runFinalization();
                    System.gc();
                    int newSize = map.Size();
                    Assert.IsTrue(size >= newSize, "previousSize(" + size + ")>=newSize(" + newSize + ")");
                    size = newSize;
                    Thread.Sleep(new TimeSpan(100L));
                    int c = 0;
                    for (IEnumerator <object> it = map.Keys.GetEnumerator(); it.MoveNext();)
                    {
                        Assert.IsNotNull(it.Current);
                        c++;
                    }
                    newSize = map.Size();
                    Assert.IsTrue(size >= c, "previousSize(" + size + ")>=iteratorSize(" + c + ")");
                    Assert.IsTrue(c >= newSize, "iteratorSize(" + c + ")>=newSize(" + newSize + ")");
                    size = newSize;
                }
                catch (ThreadInterruptedException ie)
                {
                }
            }
        }
Beispiel #13
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void shouldShutdownEvenThoughWaitingForLock0(org.neo4j.causalclustering.discovery.Cluster<?> cluster, int victimId, java.util.Collection<int> shutdownOrder) throws Exception
        private void ShouldShutdownEvenThoughWaitingForLock0 <T1>(Cluster <T1> cluster, int victimId, ICollection <int> shutdownOrder)
        {
            const int longTime = 60_000;
            const int numberOfLockAcquirers = 2;

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

            // serially, not on the main thread.

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

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

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

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

            CreateANode(node);

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

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

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

                // then shutdown in given order works
                preShutdown.complete(null);
                afterShutdown.get(longTime, MILLISECONDS);
            }
            finally
            {
                afterShutdown.cancel(true);
                locksHolder.Signal();
                txExecutor.shutdownNow();
                shutdownExecutor.shutdownNow();
            }
        }