Esempio n. 1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldNotifyCancelListeners()
        public virtual void ShouldNotifyCancelListeners()
        {
            // GIVEN
            CentralJobScheduler centralJobScheduler = new CentralJobScheduler();

            centralJobScheduler.Init();

            // WHEN
            AtomicBoolean halted = new AtomicBoolean();
            ThreadStart   job    = () =>
            {
                while (!halted.get())
                {
                    LockSupport.parkNanos(MILLISECONDS.toNanos(10));
                }
            };
            JobHandle handle = centralJobScheduler.Schedule(Group.INDEX_POPULATION, job);

            handle.RegisterCancelListener(mayBeInterrupted => halted.set(true));
            handle.Cancel(false);

            // THEN
            assertTrue(halted.get());
            centralJobScheduler.Shutdown();
        }
Esempio n. 2
0
        private void Collect(ProblemReporter report)
        {
            bool collect = Collects(report.Type());

            if (collect)
            {
                // This type of problem is collected and we're within the max threshold, so it's OK
                long count = _badEntries.incrementAndGet();
                if (_tolerance == UNLIMITED_TOLERANCE || count <= _tolerance)
                {
                    // We're within the threshold
                    if (_logBadEntries)
                    {
                        // Send this to the logger... but first apply some back pressure if queue is growing big
                        while (_queueSize.sum() >= _backPressureThreshold)
                        {
                            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
                        }
                        _logger.send(report);
                        _queueSize.add(1);
                    }
                    return;                              // i.e. don't treat this as an exception
                }
            }

            InputException exception = report.Exception();

            throw collect?withMessage(exception, format( "Too many bad entries %d, where last one was: %s", _badEntries.longValue(), exception.Message )) : exception;
        }
Esempio n. 3
0
        private bool IsDeadlockReal(ForsetiLockManager.Lock @lock, int tries)
        {
            ISet <ForsetiLockManager.Lock> waitedUpon     = new HashSet <ForsetiLockManager.Lock>();
            ISet <ForsetiClient>           owners         = new HashSet <ForsetiClient>();
            ISet <ForsetiLockManager.Lock> nextWaitedUpon = new HashSet <ForsetiLockManager.Lock>();
            ISet <ForsetiClient>           nextOwners     = new HashSet <ForsetiClient>();

            @lock.CollectOwners(owners);

            do
            {
                waitedUpon.addAll(nextWaitedUpon);
                CollectNextOwners(waitedUpon, owners, nextWaitedUpon, nextOwners);
                if (nextOwners.Contains(this) && tries > 20)
                {
                    // Worrying... let's take a deep breath
                    nextOwners.Clear();
                    LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
                    // ... and check again
                    CollectNextOwners(waitedUpon, owners, nextWaitedUpon, nextOwners);
                    if (nextOwners.Contains(this))
                    {
                        // Yes, this deadlock looks real.
                        return(true);
                    }
                }
                owners.Clear();
                ISet <ForsetiClient> ownersTmp = owners;
                owners     = nextOwners;
                nextOwners = ownersTmp;
            } while (nextWaitedUpon.Count > 0);
            // Nope, we didn't find any real wait cycles.
            return(false);
        }
Esempio n. 4
0
 private void ParkEvictor(long parkNanos)
 {
     // Only called from the background eviction thread!
     _evictorParked = true;
     LockSupport.parkNanos(this, parkNanos);
     _evictorParked = false;
 }
Esempio n. 5
0
 public override void Run()
 {
     while (!StopFlag.get())
     {
         try
         {
             using (Transaction transaction = outerInstance.EmbeddedDatabase.beginTx())
             {
                 bool deleteOnBands = ThreadLocalRandom.current().nextBoolean();
                 if (deleteOnBands)
                 {
                     DeleteRelationshipOfRandomType();
                 }
                 else
                 {
                     DeleteRelationshipOnRandomNode();
                 }
                 transaction.Success();
                 RemovalCount++;
             }
         }
         catch (Exception ignored) when(ignored is DeadlockDetectedException || ignored is NotFoundException)
         {
             // ignore deadlocks
         }
         LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(15));
     }
 }
 private void WaitOpenCallsToClose()
 {
     while (_openCalls.intValue() > 0)
     {
         LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
     }
 }
Esempio n. 7
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertThreadIsWaitingForLock(LockAcquisition lockAcquisition) throws Exception
        private void AssertThreadIsWaitingForLock(LockAcquisition lockAcquisition)
        {
            for (int i = 0; i < 30 && !Suite.isAwaitingLockAcquisition(lockAcquisition.Executor.waitUntilWaiting()); i++)
            {
                LockSupport.parkNanos(MILLISECONDS.toNanos(100));
            }
            assertFalse("locking thread completed", lockAcquisition.Completed());
        }
Esempio n. 8
0
 internal virtual void Park(long time, TimeUnit unit)
 {
     if (compareAndSet(STATE_QUEUED, STATE_PARKED))
     {
         LockSupport.parkNanos(unit.toNanos(time));
         compareAndSet(STATE_PARKED, STATE_QUEUED);
     }
 }
Esempio n. 9
0
 public override void Run()
 {
     while (!End)
     {
         Buffer.maintenance();
         LockSupport.parkNanos(NanoInterval);
     }
 }
 public override bool RetryOn(Exception t)
 {
     if (_retriable.test(t))
     {
         LockSupport.parkNanos(_unit.toNanos(_timeBetweenTries));
         return(_retries++ < _maxRetryCount);
     }
     return(false);
 }
Esempio n. 11
0
        public virtual void await(long millis)
        {
            if (Thread.CurrentThread != consumer)
            {
                throw new Exception("Wrong usage of SingleConsumerCondition: can only await in consumer thread.");
            }

            // NOTE: may spuriously return before deadline
            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(millis));
        }
Esempio n. 12
0
        protected internal override void DoWork()
        {
            GraphDatabaseService db = _dbRef.get();

            Db.shutdown();
            LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));
            bool replaced = _dbRef.compareAndSet(db, _factory.newInstance());

            assertTrue(replaced);
        }
Esempio n. 13
0
 private void TerminateAllWaitersAndWaitForClientsToLeave()
 {
     TerminateAllWaiters();
     // wait for all active clients to go and terminate latecomers
     while (_stateHolder.hasActiveClients())
     {
         TerminateAllWaiters();
         LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(20));
     }
 }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void awaitSchemaStateCleared(String keyForProbing) throws org.neo4j.internal.kernel.api.exceptions.TransactionFailureException
        private void AwaitSchemaStateCleared(string keyForProbing)
        {
            using (Transaction transaction = _kernel.beginTransaction(@implicit, AUTH_DISABLED))
            {
                while (transaction.SchemaRead().schemaStateGetOrCreate(keyForProbing, ignored => null) != null)
                {
                    LockSupport.parkNanos(MILLISECONDS.toNanos(10));
                }
                transaction.Success();
            }
        }
Esempio n. 15
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: protected void doWork() throws Exception
        protected internal override void DoWork()
        {
            BackupResult backupResult = BackupHelper.backup(_backupHostname, _backupPort, _backupDir);

            if (!backupResult.Consistent)
            {
                throw new Exception("Inconsistent backup");
            }
            if (backupResult.TransientErrorOnBackup)
            {
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
            }
        }
Esempio n. 16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test @RepeatRule.Repeat(times = 5) public void concurrentLabelTokenCreation() throws InterruptedException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConcurrentLabelTokenCreation()
        {
            int concurrentWorkers = 10;

            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(concurrentWorkers);
            for (int i = 0; i < concurrentWorkers; i++)
            {
                (new LabelCreator(this, DatabaseRule, latch)).Start();
            }
            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(500));
            _stop = true;
            latch.await();
        }
Esempio n. 17
0
        public static void AwaitForever(System.Func <bool> condition, long checkInterval, TimeUnit unit)
        {
            long sleep = unit.toNanos(checkInterval);

            do
            {
                if (condition())
                {
                    return;
                }
                LockSupport.parkNanos(sleep);
            } while (true);
        }
Esempio n. 18
0
 public override void Run()
 {
     _timeKeeper = Thread.CurrentThread;
     while (!_stopped)
     {
         long timeToNextTickNanos = Tick();
         if (_stopped)
         {
             return;
         }
         LockSupport.parkNanos(this, timeToNextTickNanos);
     }
 }
Esempio n. 19
0
 public override void Run()
 {
     while (!StopFlag.get())
     {
         using (Transaction transaction = outerInstance.EmbeddedDatabase.beginTx())
         {
             Node randomBandNode = outerInstance.getRandomBandNode(outerInstance.EmbeddedDatabase, BandLabel);
             RelationshipSize = Iterables.asList(randomBandNode.RelationshipTypes).Count;
             transaction.Success();
         }
         long millisToWait = ThreadLocalRandom.current().nextLong(10, 25);
         LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(millisToWait));
     }
 }
Esempio n. 20
0
        /// <summary>
        /// 结束运行 依次唤醒等待get结果的节点 带超时机制
        /// </summary>
        /// <param name="timed"></param>
        /// <param name="nanos"></param>
        /// <returns></returns>
        private int awaitDone(bool timed, long nanos)
        {
            long     deadline = timed ? DateTime.Now.Ticks + nanos : 0L;
            WaitNode q        = null;
            bool     queued   = false;

            for (; ;)
            {
                //if (Thread.interrupted()) {
                //    removeWaiter(q);
                //    throw new ThreadInterruptedException();
                //}
                int s = state;
                if (s > COMPLETING)
                {
                    if (q != null)
                    {
                        q.thread = null;
                    }
                    return(s);
                }
                else if (s == COMPLETING)// cannot time out yet
                {
                    Thread.Yield();
                }
                else if (q == null)
                {
                    q = new WaitNode();
                }
                else if (!queued)
                {
                    queued = Interlocked.CompareExchange <WaitNode>(ref waiters, q, q.next = waiters) == q.next;
                }
                else if (timed)
                {
                    nanos = deadline - DateTime.Now.Ticks;
                    if (nanos <= 0L)
                    {
                        removeWaiter(q);
                        return(state);
                    }
                    LockSupport.parkNanos(this, nanos);
                }
                else
                {
                    LockSupport.park(this);
                }
            }
        }
Esempio n. 21
0
        private void PeriodicallyPullUpdates()
        {
            while (!_halted)
            {
                int round = _targetTicket.get();
                if (_currentTicket.get() < round)
                {
                    DoPullUpdates();
                    _currentTicket.set(round);
                    continue;
                }

                LockSupport.parkNanos(ParkNanos);
            }
        }
Esempio n. 22
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public static <EXCEPTION extends Exception> boolean tryAwaitEx(ThrowingSupplier<bool,EXCEPTION> condition, long timeout, java.util.concurrent.TimeUnit timeoutUnit, long pollInterval, java.util.concurrent.TimeUnit pollUnit, java.time.Clock clock) throws EXCEPTION
        public static bool TryAwaitEx <EXCEPTION>(ThrowingSupplier <bool, EXCEPTION> condition, long timeout, TimeUnit timeoutUnit, long pollInterval, TimeUnit pollUnit, Clock clock) where EXCEPTION : Exception
        {
            long deadlineMillis    = clock.millis() + timeoutUnit.toMillis(timeout);
            long pollIntervalNanos = pollUnit.toNanos(pollInterval);

            do
            {
                if (condition.Get())
                {
                    return(true);
                }
                LockSupport.parkNanos(pollIntervalNanos);
            } while (clock.millis() < deadlineMillis);
            return(false);
        }
Esempio n. 23
0
        private long Sleep(long baselineNanos, long delayNanoes)
        {
            long nextBaseline = System.nanoTime();
            long sleepNanos   = delayNanoes - (nextBaseline - baselineNanos);

            if (sleepNanos > 0)
            {
                LockSupport.parkNanos(this, sleepNanos);
            }
            else
            {
                _underSampling.AndIncrement;
                Thread.yield();                         // The sampler thread runs with slightly elevated priority, so we yield to give the profiled thread a chance to run.
            }
            return(nextBaseline + delayNanoes);
        }
Esempio n. 24
0
        /// <summary>
        /// 共享模式下请求资源 带超时机制
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="nanosTimeout"></param>
        /// <returns></returns>
        private bool doAcquireSharedNanos(int arg,long nanosTimeout)
        {
            if (nanosTimeout <= 0L)
            {
                return(false);
            }
            long deadline = DateTime.Now.Ticks + nanosTimeout;
            Node node     = AddWaiter(Node.SHARED);
            bool failed   = true;

            try
            {
                for (; ;)
                {
                    Node p = node.Predecessor;
                    if (p == head)
                    {
                        int r = tryAcquireShared(arg);
                        if (r >= 0)
                        {
                            setHeadAndPropagate(node,r);
                            p.Next = null; // help GC
                            failed = false;
                            return(true);
                        }
                    }
                    nanosTimeout = deadline - DateTime.Now.Ticks;
                    if (nanosTimeout <= 0L)
                    {
                        return(false);
                    }
                    if (shouldParkAfterFailedAcquire(p,node) && nanosTimeout > spinForTimeoutThreshold)
                    {
                        LockSupport.parkNanos(this,nanosTimeout);
                    }
                }
            }
            finally
            {
                if (failed)
                {
                    cancelAcquire(node);
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// 独占模式下请求资源 带超时时间
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="nanosTimeout"></param>
        /// <returns></returns>
        private bool doAcquireNanos(int arg,long nanosTimeout)
        {
            if (nanosTimeout <= 0L)
            {
                return(false);
            }
            long deadline = DateTime.Now.Ticks + nanosTimeout;
            Node node     = AddWaiter(Node.EXCLUSIVE);
            bool failed   = true;

            try
            {
                for (; ;)
                {
                    Node p = node.Predecessor;
                    if (p == head && tryAcquire(arg))
                    {
                        Head   = node;
                        p.Next = null; // help GC
                        failed = false;
                        return(true);
                    }
                    nanosTimeout = deadline - DateTime.Now.Ticks;
                    if (nanosTimeout <= 0L)
                    {
                        return(false);
                    }
                    if (shouldParkAfterFailedAcquire(p,node) && nanosTimeout > spinForTimeoutThreshold)
                    {
                        LockSupport.parkNanos(this,nanosTimeout);
                    }
                    //if (Thread.interrupted())
                    //{
                    //    throw new InterruptedException();
                    //}
                }
            }
            finally
            {
                if (failed)
                {
                    cancelAcquire(node);
                }
            }
        }
Esempio n. 26
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test(timeout = 10_000) public void waitTerminationOnDelayedJobMustWaitUntilJobCompletion() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void WaitTerminationOnDelayedJobMustWaitUntilJobCompletion()
        {
            CentralJobScheduler scheduler = new CentralJobScheduler();

            scheduler.Init();

            AtomicBoolean triggered = new AtomicBoolean();
            ThreadStart   job       = () =>
            {
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
                triggered.set(true);
            };

            JobHandle handle = scheduler.Schedule(Group.INDEX_POPULATION, job, 10, TimeUnit.MILLISECONDS);

            handle.WaitTermination();
            assertTrue(triggered.get());
        }
Esempio n. 27
0
            public override void Run()
            {
                while (!StopFlag.get())
                {
                    int newRelationships = 0;
                    try
                    {
                        using (Transaction transaction = outerInstance.EmbeddedDatabase.beginTx())
                        {
                            Node bandNode  = outerInstance.getRandomBandNode(outerInstance.EmbeddedDatabase, BandLabel);
                            int  direction = ThreadLocalRandom.current().Next(3);
                            switch (direction)
                            {
                            case 0:
                                newRelationships += ConnectCitiesToBand(bandNode);
                                break;

                            case 1:
                                newRelationships += ConnectBandToCities(bandNode);
                                break;

                            case 2:
                                newRelationships += ConnectCitiesToBand(bandNode);
                                newRelationships += ConnectBandToCities(bandNode);
                                break;

                            default:
                                throw new System.InvalidOperationException("Unsupported direction value:" + direction);
                            }
                            transaction.Success();
                        }
                    }
                    catch (DeadlockDetectedException)
                    {
                        // deadlocks ignored
                    }
                    CreatedRelationshipsConflict += newRelationships;
                    long millisToWait = ThreadLocalRandom.current().nextLong(10, 30);
                    LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(millisToWait));
                }
            }
Esempio n. 28
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void assertOnlyOneSucceeds(Runnable lockAction1, Runnable lockAction2) throws Throwable
        private void AssertOnlyOneSucceeds(ThreadStart lockAction1, ThreadStart lockAction2)
        {
            AssertUU();
            Race           race = new Race();
            LockContestant c1   = new LockContestant(lockAction1);
            LockContestant c2   = new LockContestant(lockAction2);

            // when
            race.AddContestant(c1);
            race.AddContestant(c2);

            race.GoAsync();
            while (!(c1.LockAcquired() || c2.LockAcquired()) || !(c1.Started() && c2.Started()))
            {
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
            }

            // then
            Pair <bool, bool> c1State = c1.State();
            Pair <bool, bool> c2State = c2.State();

            assertNotEquals(WithState("Expected exactly one to acquire lock.", c1State, c2State), c1State.First(), c2State.First());
            assertTrue(WithState("Expected both to be started.", c1State, c2State), c1State.Other() && c2State.Other());
        }
Esempio n. 29
0
 private static void ParkAWhile()
 {
     LockSupport.parkNanos(MILLISECONDS.toNanos(100));
 }
        private void WaitForLogForce()
        {
            long parkTime = TimeUnit.MILLISECONDS.toNanos(100);

            LockSupport.parkNanos(this, parkTime);
        }