コード例 #1
0
        /// <summary>
        /// 唤醒下一个等待线程
        /// </summary>
        /// <param name="node"></param>
        private void UnparkSuccessor(Node node)
        {
            int ws = node.WaitStatus;

            if (ws < 0)
            {
                CompareAndSetWaitStatus(node, ws, 0);
            }
            Node s = node.Next;

            //节点为null或者已经取消 则寻找下一个节点
            if (s == null || s.WaitStatus > 0)
            {
                s = null;
                //从后向前找最前面可以被唤醒的节点 不知道为什么不从前往后找
                for (Node t = Tail; t != null && t != node; t = t.Prev)
                {
                    if (t.WaitStatus <= 0)
                    {
                        s = t;
                    }
                }
            }
            //唤醒该节点线程
            if (s != null)
            {
                LockSupport.unpark(s.Thread);
            }
        }
コード例 #2
0
        /// <summary>
        /// Removes and signals all waiting threads, invokes done(), and
        /// nulls out callable.
        /// </summary>
        private void FinishCompletion()
        {
            // assert state > COMPLETING;
            for (WaitNode q; (q = Waiters) != null;)
            {
                if (UNSAFE.compareAndSwapObject(this, WaitersOffset, q, null))
                {
                    for (;;)
                    {
                        Thread t = q.thread;
                        if (t != null)
                        {
                            q.thread = null;
                            LockSupport.Unpark(t);
                        }
                        WaitNode next = q.next;
                        if (next == null)
                        {
                            break;
                        }
                        q.next = null;                         // unlink to help gc
                        q      = next;
                    }
                    break;
                }
            }

            Done();

            Callable = null;             // to reduce footprint
        }
コード例 #3
0
        private int Poke()
        {
            int result = this._targetTicket.incrementAndGet();

            LockSupport.unpark(_updatePullingThread);
            return(result);
        }
コード例 #4
0
ファイル: BadCollector.cs プロジェクト: Neo4Net/Neo4Net
        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;
        }
コード例 #5
0
 /// <summary>
 /// 结束运行 依次唤醒等待get结果的节点
 /// </summary>
 private void finishCompletion()
 {
     // assert state > COMPLETING;
     for (WaitNode q; (q = waiters) != null;)
     {
         if (Interlocked.CompareExchange <WaitNode>(ref waiters, null, q) == q)
         {
             for (; ;)
             {
                 Thread t = q.thread;
                 if (t != null)
                 {
                     q.thread = null;
                     LockSupport.unpark(t);
                 }
                 WaitNode next = q.next;
                 if (next == null)
                 {
                     break;
                 }
                 q.next = null; // unlink to help gc
                 q      = next;
             }
             break;
         }
     }
     done();
     callable = null;        // to reduce footprint
 }
コード例 #6
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();
        }
コード例 #7
0
ファイル: AsyncEvents.cs プロジェクト: Neo4Net/Neo4Net
        public override void Run()
        {
            Debug.Assert(_backgroundThread == null, "A thread is already running " + _backgroundThread);
            _backgroundThread = Thread.CurrentThread;
            _startupLatch.release();

            try
            {
                do
                {
                    AsyncEvent events = _stackUpdater.getAndSet(this, _endSentinel);
                    Process(events);
                    if (_stack == _endSentinel && !_shutdown)
                    {
                        LockSupport.park(this);
                    }
                } while (!_shutdown);

                AsyncEvent events = _stackUpdater.getAndSet(this, _shutdownSentinel);
                Process(events);
            }
            finally
            {
                _backgroundThread = null;
                _shutdownLatch.release();
            }
        }
コード例 #8
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));
     }
 }
コード例 #9
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);
        }
コード例 #10
0
 private void ParkEvictor(long parkNanos)
 {
     // Only called from the background eviction thread!
     _evictorParked = true;
     LockSupport.parkNanos(this, parkNanos);
     _evictorParked = false;
 }
コード例 #11
0
ファイル: ThreadAhead.cs プロジェクト: Neo4Net/Neo4Net
 public override void Run()
 {
     while (!_closed)
     {
         if (_hasReadAhead || _eof)
         {                         // We have already read ahead, sleep a little
             ParkAWhile();
         }
         else
         {                         // We haven't read ahead, or the data we read ahead have been consumed
             try
             {
                 if (!ReadAhead())
                 {
                     _eof = true;
                 }
                 _hasReadAhead = true;
                 LockSupport.unpark(_owner);
             }
             catch (IOException e)
             {
                 _ioException = e;
                 _closed      = true;
             }
             catch (Exception e)
             {
                 _ioException = new IOException(e);
                 _closed      = true;
             }
         }
     }
 }
コード例 #12
0
 private void WaitOpenCallsToClose()
 {
     while (_openCalls.intValue() > 0)
     {
         LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
     }
 }
コード例 #13
0
ファイル: StopCompatibility.cs プロジェクト: Neo4Net/Neo4Net
//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());
        }
コード例 #14
0
 public override void Run()
 {
     while (!End)
     {
         Buffer.maintenance();
         LockSupport.parkNanos(NanoInterval);
     }
 }
コード例 #15
0
 private void UnparkEvictor()
 {
     if (_evictorParked)
     {
         _evictorParked = false;
         LockSupport.unpark(_evictionThread);
     }
 }
コード例 #16
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);
     }
 }
コード例 #17
0
 public override bool RetryOn(Exception t)
 {
     if (_retriable.test(t))
     {
         LockSupport.parkNanos(_unit.toNanos(_timeBetweenTries));
         return(_retries++ < _maxRetryCount);
     }
     return(false);
 }
コード例 #18
0
ファイル: BinaryLatch.cs プロジェクト: Neo4Net/Neo4Net
 private void UnparkSuccessor(Node waiters)
 {
     if (waiters.GetType() == typeof(Waiter))
     {
         Waiter waiter = ( Waiter )waiters;
         waiter.State = WAITER_STATE_SUCCESSOR;
         LockSupport.unpark(waiter.WaitingThread);
     }
 }
コード例 #19
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));
     }
 }
コード例 #20
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));
        }
コード例 #21
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);
        }
コード例 #22
0
//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();
            }
        }
コード例 #23
0
 /// <summary>
 /// 线程休眠且检查是否被中断唤醒 这儿可能有问题!!!!!
 /// </summary>
 /// <returns></returns>
 private bool parkAndCheckInterrupt()
 {
     try
     {
         LockSupport.park(this);
         return(true);
     }
     catch (ThreadInterruptedException e)
     {
         return(false);
     }
 }
コード例 #24
0
        /// <summary>
        /// Awaits completion or aborts on interrupt or timeout.
        /// </summary>
        /// <param name="timed"> true if use timed waits </param>
        /// <param name="nanos"> time to wait, if timed </param>
        /// <returns> state upon completion </returns>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private int awaitDone(boolean timed, long nanos) throws InterruptedException
        private int AwaitDone(bool timed, long nanos)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final long deadline = timed ? System.nanoTime() + nanos : 0L;
            long     deadline = timed ? System.nanoTime() + nanos : 0L;
            WaitNode q        = null;
            bool     queued   = false;

            for (;;)
            {
                if (Thread.Interrupted())
                {
                    RemoveWaiter(q);
                    throw new InterruptedException();
                }

                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 = UNSAFE.compareAndSwapObject(this, WaitersOffset, q.Next = Waiters, q);
                }
                else if (timed)
                {
                    nanos = deadline - System.nanoTime();
                    if (nanos <= 0L)
                    {
                        RemoveWaiter(q);
                        return(State);
                    }
                    LockSupport.ParkNanos(this, nanos);
                }
                else
                {
                    LockSupport.Park(this);
                }
            }
        }
コード例 #25
0
ファイル: Predicates.cs プロジェクト: Neo4Net/Neo4Net
        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);
        }
コード例 #26
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));
            }
        }
コード例 #27
0
 public override void Run()
 {
     _timeKeeper = Thread.CurrentThread;
     while (!_stopped)
     {
         long timeToNextTickNanos = Tick();
         if (_stopped)
         {
             return;
         }
         LockSupport.parkNanos(this, timeToNextTickNanos);
     }
 }
コード例 #28
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();
        }
コード例 #29
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));
     }
 }
コード例 #30
0
        public override void Stop()          // for removing throw declaration
        {
            if (_shutdownLatch == null)
            {
                return;                         // This SlaveUpdatePuller has already been shut down
            }

            Thread thread = _updatePullingThread;

            _halted = true;
            LockSupport.unpark(thread);
            _shutdownLatch.await();
            _shutdownLatch = null;
        }