Disruptor 源码分析(9) 不同等待策略之间的区别
disruptor 不同等待策略之间的区别
几个策略其实没有太多的区别,主要是--counter , Thread.yield(), LockSupport.parkNanos(1L),lock.lock(),超时抛异常其中的一种货多种的组合.
WaitStrategy有好几个实现类:
SleepingWaitStrategy 是这样的
while ((availableSequence = dependentSequence.get()) < sequence) { counter = applyWaitMethod(barrier, counter); } private int applyWaitMethod(final SequenceBarrier barrier, int counter) throws AlertException { barrier.checkAlert(); if (counter > 100) { --counter; } else if (counter > 0) { --counter; Thread.yield(); } else { LockSupport.parkNanos(1L); }
do { if ((availableSequence = dependentSequence.get()) >= sequence) { return availableSequence; } if (0 == --counter) { if (0 == startTime) { startTime = System.nanoTime(); } else { long timeDelta = System.nanoTime() - startTime; if (timeDelta > yieldTimeoutNanos) { return lockingStrategy.waitOnLock(sequence, cursor, dependentSequence, barrier); } else if (timeDelta > spinTimeoutNanos) { Thread.yield(); } } counter = SPIN_TRIES; } } while (true);
while ((availableSequence = dependentSequence.get()) < sequence) { barrier.checkAlert(); }
lock.lock(); try { while ((availableSequence = cursorSequence.get()) < sequence) { barrier.checkAlert(); nanos = processorNotifyCondition.awaitNanos(nanos); if (nanos <= 0) { throw TimeoutException.INSTANCE; }
while ((availableSequence = dependentSequence.get()) < sequence) { counter = applyWaitMethod(barrier, counter); } private int applyWaitMethod(final SequenceBarrier barrier, int counter) throws AlertException { if (0 == counter) { Thread.yield(); } else { --counter; }