Beispiel #1
0
 public override void Run()
 {
     while (KeepRunning)
     {
         Task.run();
     }
 }
Beispiel #2
0
 internal ScheduledJobHandle(TimeBasedTaskScheduler scheduler, Group group, ThreadStart task, long nextDeadlineNanos, long reschedulingDelayNanos)
 {
     this._group            = group;
     this.NextDeadlineNanos = nextDeadlineNanos;
     _handleRelease         = new BinaryLatch();
     _cancelListeners       = new CopyOnWriteArrayList <CancelListener>();
     this._task             = () =>
     {
         try
         {
             task.run();
             // Use compareAndSet to avoid overriding any cancellation state.
             if (compareAndSet(SUBMITTED, RUNNABLE) && reschedulingDelayNanos > 0)
             {
                 // We only reschedule if the rescheduling delay is greater than zero.
                 // A rescheduling delay of zero means this is a delayed task.
                 // If the rescheduling delay is greater than zero, then this is a recurring task.
                 this.NextDeadlineNanos += reschedulingDelayNanos;
                 scheduler.EnqueueTask(this);
             }
         }
         catch (Exception e)
         {
             _lastException = e;
             set(FAILED);
         }
     };
 }
Beispiel #3
0
        public override void EndBlock()
        {
            ThreadStart action = _levels.pop();

            Indent().Append("}\n");
            action.run();
        }
        private void NumberOperation(TypeReference type, ThreadStart onInt, ThreadStart onLong, ThreadStart onFloat, ThreadStart onDouble)
        {
            if (!type.Primitive)
            {
                throw new System.InvalidOperationException("Cannot compare reference types");
            }

            switch (type.Name())
            {
            case "int":
            case "byte":
            case "short":
            case "char":
            case "boolean":
                onInt.run();
                break;

            case "long":
                onLong.run();
                break;

            case "float":
                onFloat.run();
                break;

            case "double":
                onDouble.run();
                break;

            default:
                throw new System.InvalidOperationException("Cannot compare reference types");
            }
        }
Beispiel #5
0
        public virtual void test_runnable_fail2()
        {
            ThreadStart a = Unchecked.runnable(() =>
            {
                throw new Exception();
            });

            assertThrows(() => a.run(), typeof(Exception));
        }
Beispiel #6
0
 public override void Release()
 {
     if (Released)
     {
         throw new System.InvalidOperationException("Already released");
     }
     Released = true;
     ReleaseConflict.run();
 }
            public override long Next()
            {
                long value = Delegate.next();

                if (!HasNext())
                {
                    CustomAction.run();
                }
                return(value);
            }
Beispiel #8
0
 public override void Execute(ThreadStart command)
 {
     if (_executor != null)
     {
         _executor.execute(command);
     }
     else
     {
         command.run();
     }
 }
Beispiel #9
0
 public override void close()
 {
     try
     {
         _closeAction.run();
     }
     finally
     {
         base.close();
     }
 }
Beispiel #10
0
 private void AssertThrow(ThreadStart unlock)
 {
     try
     {
         unlock.run();
         fail("Should have failed");
     }
     catch (System.InvalidOperationException)
     {
         // good
     }
 }
Beispiel #11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertBlock(Runnable runLock, Runnable runUnlock) throws Exception
        private void AssertBlock(ThreadStart runLock, ThreadStart runUnlock)
        {
            Future <object> future = Executor.execute(state =>
            {
                runLock.run();
                return(null);
            });

            Executor.get().waitUntilWaiting(details => details.isAt(typeof(GBPTreeLock), "doLock"));
            runUnlock.run();
            future.get();
        }
Beispiel #12
0
            public override long?Call()
            {
                long endTime = DateTimeHelper.CurrentUnixTimeMillis() + RunTimeMillis;
                long count   = 0;

                while (endTime > DateTimeHelper.CurrentUnixTimeMillis())
                {
                    Task.run();
                    count++;
                }
                return(count);
            }
Beispiel #13
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public void withServer(String json, Runnable test) throws Exception
        public virtual void WithServer(string json, ThreadStart test)
        {
            Server server = setUp(json);

            try
            {
                test.run();
            }
            finally
            {
                TearDown(server);
            }
        }
Beispiel #14
0
        private static void AssertThatFails(Type exceptionClass, ThreadStart action)
        {
            try
            {
                action.run();
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                fail("Expected exception was not thrown: " + exceptionClass.FullName);
            }
            catch (Exception e)
            {
                assertSame(exceptionClass, e.GetType());
            }
        }
Beispiel #15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void executeTransactionInSeparateThread(final Runnable actionInsideTransaction) throws InterruptedException
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
        private void ExecuteTransactionInSeparateThread(ThreadStart actionInsideTransaction)
        {
            Thread thread = new Thread(() =>
            {
                using (Transaction tx = Db.beginTx())
                {
                    actionInsideTransaction.run();
                    tx.success();
                }
            });

            thread.Start();
            thread.Join();
        }
Beispiel #16
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
//ORIGINAL LINE: public static void doContextSwitch(final Runnable runnable, org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity contextDefinition)
        public static void doContextSwitch(ThreadStart runnable, ProcessDefinitionEntity contextDefinition)
        {
            ProcessApplicationReference processApplication = getTargetProcessApplication(contextDefinition);

            if (requiresContextSwitch(processApplication))
            {
                Context.executeWithinProcessApplication(new CallableAnonymousInnerClass(runnable)
                                                        , processApplication);
            }
            else
            {
                runnable.run();
            }
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public org.neo4j.graphdb.mockfs.EphemeralFileSystemAbstraction snapshot(Runnable action) throws Exception
        public virtual EphemeralFileSystemAbstraction Snapshot(ThreadStart action)
        {
            EphemeralFileSystemAbstraction snapshot = Fs.snapshot();

            try
            {
                action.run();
            }
            finally
            {
                Fs.close();
                Fs = snapshot;
            }
            return(Fs);
        }
Beispiel #18
0
        protected internal virtual void runAsUser(string userId, IList <string> groupIds, ThreadStart r)
        {
            try
            {
                identityService.AuthenticatedUserId             = userId;
                processEngineConfiguration.AuthorizationEnabled = true;

                r.run();
            }
            finally
            {
                identityService.AuthenticatedUserId             = null;
                processEngineConfiguration.AuthorizationEnabled = false;
            }
        }
Beispiel #19
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static void execute(java.util.List<ConsistencyCheckerTask> tasks, Runnable callBefore) throws ConsistencyCheckIncompleteException
        public static void Execute(IList <ConsistencyCheckerTask> tasks, ThreadStart callBefore)
        {
            try
            {
                foreach (ThreadStart task in tasks)
                {
                    callBefore.run();
                    task.run();
                }
            }
            catch (Exception e)
            {
                throw new ConsistencyCheckIncompleteException(e);
            }
        }
Beispiel #20
0
 public virtual void run()
 {
     try
     {
         @delegate.run();
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
         Console.Write(e.StackTrace);
     }
     finally
     {
         latch.Signal();
     }
 }
Beispiel #21
0
 public override void Execute(ThreadStart runnable)
 {
     if (_latch.compareAndSet(false, true))
     {
         _jobScheduler.schedule(_group, () =>
         {
             try
             {
                 runnable.run();
             }
             finally
             {
                 _latch.set(false);
             }
         });
     }
 }
Beispiel #22
0
 internal virtual bool TryTrigger()
 {
     if (outerInstance.now() >= Deadline)
     {
         Runnable.run();
         if (Period != 0)
         {
             Deadline += Period;
         }
         else
         {
             outerInstance.jobs.remove(this);
         }
         return(true);
     }
     return(false);
 }
 /// <summary>
 /// Cancels population also executing a specific operation on the populator </summary>
 /// <param name="specificPopulatorOperation"> specific operation in addition to closing the populator. </param>
 internal virtual void Cancel(ThreadStart specificPopulatorOperation)
 {
     PopulatorLock.@lock();
     try
     {
         if (PopulationOngoing)
         {
             // First of all remove this population from the list of ongoing populations so that it won't receive more updates.
             // This is good because closing the populator may wait for an opportunity to perform the close, among the incoming writes to it.
             outerInstance.removeFromOngoingPopulations(this);
             specificPopulatorOperation.run();
             outerInstance.resetIndexCountsForPopulation(this);
             PopulationOngoing = false;
         }
     }
     finally
     {
         PopulatorLock.unlock();
     }
 }
Beispiel #24
0
        public JobHandle Submit(ThreadStart job)
        {
            object      registryKey   = new object();
            ThreadStart registeredJob = () =>
            {
                try
                {
                    job.run();
                }
                finally
                {
                    _registry.Remove(registryKey);
                }
            };
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.concurrent.Future<?> future = executor.submit(registeredJob);
            Future <object> future = _executor.submit(registeredJob);

            _registry[registryKey] = future;
            return(new PooledJobHandle(future, registryKey, _registry));
        }
Beispiel #25
0
 /// <summary>
 /// Capture system err for testing.
 /// <para>
 /// This returns the output from calls to {@code System.err}.
 /// This is thread-safe, providing that no other utility alters system out.
 /// </para>
 /// <para>
 /// For example:
 /// <pre>
 ///  String sysErr = captureSystemErr(() -> myCode);
 /// </pre>
 ///
 /// </para>
 /// </summary>
 /// <param name="runner">  the lambda containing the code to test </param>
 /// <returns> the captured output </returns>
 public static string caputureSystemErr(ThreadStart runner)
 {
     lock (typeof(TestHelper))
     {
         // it would be possible to use some form of thread-local PrintStream to increase concurrency,
         // but that should be done only if synchronized is insufficient
         assertNotNull(runner, "caputureSystemErr() called with null Runnable");
         MemoryStream baos = new MemoryStream(1024);
         PrintStream  ps   = Unchecked.wrap(() => new PrintStream(baos, false, UTF_8));
         PrintStream  old  = System.err;
         try
         {
             System.Err = ps;
             runner.run();
             System.err.flush();
         }
         finally
         {
             System.Err = old;
         }
         return(Unchecked.wrap(() => baos.ToString(UTF_8)));
     }
 }
Beispiel #26
0
        /// <summary>
        /// Capture log for testing.
        /// <para>
        /// This returns the output from calls to the java logger.
        /// This is thread-safe, providing that no other utility alters the logger.
        /// </para>
        /// <para>
        /// For example:
        /// <pre>
        ///  String log = captureLog(Foo.class, () -> myCode);
        /// </pre>
        ///
        /// </para>
        /// </summary>
        /// <param name="loggerClass">  the class defining the logger to trap </param>
        /// <param name="runner">  the lambda containing the code to test </param>
        /// <returns> the captured output </returns>
        public static IList <LogRecord> caputureLog(Type loggerClass, ThreadStart runner)
        {
            lock (typeof(TestHelper))
            {
                assertNotNull(loggerClass, "caputureLog() called with null Class");
                assertNotNull(runner, "caputureLog() called with null Runnable");

//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
                Logger     logger  = Logger.getLogger(loggerClass.FullName);
                LogHandler handler = new LogHandler();
                try
                {
                    handler.Level            = Level.ALL;
                    logger.UseParentHandlers = false;
                    logger.addHandler(handler);
                    runner.run();
                    return(handler.records);
                }
                finally
                {
                    logger.removeHandler(handler);
                }
            }
        }
Beispiel #27
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldKeepItsCoolWhenMultipleThreadsAreHammeringIt() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldKeepItsCoolWhenMultipleThreadsAreHammeringIt()
        {
            // An interesting note is that during tests the call to sequence#offer made no difference
            // in performance, so there seems to be no visible penalty in using ArrayQueueOutOfOrderSequence.

            // GIVEN a sequence with intentionally low starting queue size
            System.Func <long, long[]> metaFunction = number => new long[] { number + 2, number * 2 };
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.concurrent.atomic.AtomicLong numberSource = new java.util.concurrent.atomic.AtomicLong();
            AtomicLong numberSource = new AtomicLong();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.impl.util.OutOfOrderSequence sequence = new org.neo4j.kernel.impl.util.ArrayQueueOutOfOrderSequence(numberSource.get(), 5, metaFunction.apply(numberSource.get()));
            OutOfOrderSequence sequence = new ArrayQueueOutOfOrderSequence(numberSource.get(), 5, metaFunction(numberSource.get()));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.test.Race race = new org.neo4j.test.Race().withEndCondition(() -> numberSource.get() > 10_000_000);
            Race race         = (new Race()).withEndCondition(() => numberSource.get() > 10_000_000);
            int  offerThreads = max(2, Runtime.Runtime.availableProcessors() - 1);

            race.AddContestants(offerThreads, () =>
            {
                long number = numberSource.incrementAndGet();
                sequence.Offer(number, metaFunction(number));
            });
            ThreadStart verifier = () =>
            {
                long[] highest      = sequence.Get();
                long[] expectedMeta = metaFunction(highest[0]);
                assertArrayEquals(expectedMeta, copyOfRange(highest, 1, highest.Length));
            };

            race.AddContestant(verifier);
            race.Go();

            // THEN
            verifier.run();
        }
Beispiel #28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public Void call() throws Exception
            public override Void call()
            {
                runnable.run();
                return(null);
            }
Beispiel #29
0
 public virtual void run()
 {
     runnable.run();
 }
Beispiel #30
0
 public override JobHandle Schedule(Group group, ThreadStart job)
 {
     job.run();
     return(mock(typeof(JobHandle)));
 }