|
| 1 | +package com.lmax.disruptor; |
| 2 | + |
| 3 | +import java.util.concurrent.TimeUnit; |
| 4 | +import java.util.concurrent.locks.Condition; |
| 5 | +import java.util.concurrent.locks.Lock; |
| 6 | +import java.util.concurrent.locks.ReentrantLock; |
| 7 | + |
| 8 | +import com.lmax.disruptor.AlertException; |
| 9 | +import com.lmax.disruptor.Sequence; |
| 10 | +import com.lmax.disruptor.SequenceBarrier; |
| 11 | +import com.lmax.disruptor.WaitStrategy; |
| 12 | + |
| 13 | +public class TimeoutBlockingWaitStrategy implements WaitStrategy |
| 14 | +{ |
| 15 | + private final Lock lock = new ReentrantLock(); |
| 16 | + private final Condition processorNotifyCondition = lock.newCondition(); |
| 17 | + private final long timeoutInNanos; |
| 18 | + |
| 19 | + public TimeoutBlockingWaitStrategy(final long timeout, final TimeUnit units) |
| 20 | + { |
| 21 | + timeoutInNanos = units.toNanos(timeout); |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public long waitFor(final long sequence, |
| 26 | + final Sequence cursorSequence, |
| 27 | + final Sequence dependentSequence, |
| 28 | + final SequenceBarrier barrier) |
| 29 | + throws AlertException, InterruptedException |
| 30 | + { |
| 31 | + long nanos = timeoutInNanos; |
| 32 | + |
| 33 | + long availableSequence; |
| 34 | + if ((availableSequence = cursorSequence.get()) < sequence) |
| 35 | + { |
| 36 | + lock.lock(); |
| 37 | + try |
| 38 | + { |
| 39 | + while ((availableSequence = cursorSequence.get()) < sequence) |
| 40 | + { |
| 41 | + barrier.checkAlert(); |
| 42 | + nanos = processorNotifyCondition.awaitNanos(nanos); |
| 43 | + if (nanos <= 0) |
| 44 | + { |
| 45 | + return availableSequence; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + finally |
| 50 | + { |
| 51 | + lock.unlock(); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + while ((availableSequence = dependentSequence.get()) < sequence) |
| 56 | + { |
| 57 | + barrier.checkAlert(); |
| 58 | + } |
| 59 | + |
| 60 | + return availableSequence; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void signalAllWhenBlocking() |
| 65 | + { |
| 66 | + lock.lock(); |
| 67 | + try |
| 68 | + { |
| 69 | + processorNotifyCondition.signalAll(); |
| 70 | + } |
| 71 | + finally |
| 72 | + { |
| 73 | + lock.unlock(); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments