com.lmax.disruptor.SequenceBarrier Java Examples

The following examples show how to use com.lmax.disruptor.SequenceBarrier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SleepWaitStrategyFactory.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
@Override
public long waitFor(final long sequence, Sequence cursor, final Sequence dependentSequence,
                    final SequenceBarrier barrier) throws AlertException {
    long availableSequence;
    int counter = retries;

    // dependentSequence 该项目组织架构中,其实只是生产者的sequence,也就是cursor
    while ((availableSequence = dependentSequence.get()) < sequence) {
        counter = applyWaitMethod(barrier, counter);

        // 每睡眠一次,执行一次循环
        if (counter <= 0) {
            eventLoop.safeLoopOnce();
        }
    }
    return availableSequence;
}
 
Example #2
Source File: SleepWaitStrategyFactory.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
private int applyWaitMethod(final SequenceBarrier barrier, int counter)
        throws AlertException {
    // 检查中断/终止信号
    barrier.checkAlert();

    if (counter > 100) {
        // 大于100时自旋
        --counter;
    } else if (counter > 0) {
        // 大于0时尝试让出Cpu
        --counter;
        Thread.yield();
    } else {
        // 等到最大次数了,睡眠等待
        LockSupport.parkNanos(sleepTimeNs);
    }
    return counter;
}
 
Example #3
Source File: BusySpinWaitStrategyFactory.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
@Override
public long waitFor(final long sequence, Sequence cursor, final Sequence dependentSequence,
                    final SequenceBarrier barrier) throws AlertException, InterruptedException {

    long availableSequence;
    int spinTries = 0;

    // dependentSequence 该项目组织架构中,其实只是生产者的sequence,也就是cursor
    while ((availableSequence = dependentSequence.get()) < sequence) {
        barrier.checkAlert();
        Thread.onSpinWait();

        if (++spinTries == loopOnceSpinTries) {
            spinTries = 0;
            eventLoop.safeLoopOnce();
        }
    }

    return availableSequence;
}
 
Example #4
Source File: SleepingBlockingWaitStrategy.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
public long waitFor(long sequence, Sequence cursorSequence, Sequence dependentSequence, SequenceBarrier barrier)
        throws AlertException, InterruptedException {
    if (cursorSequence.get() < sequence) {
        this.lock.lock();

        try {
            while (cursorSequence.get() < sequence) {
                barrier.checkAlert();
                this.processorNotifyCondition.await();
            }
        } finally {
            this.lock.unlock();
        }
    }

    long availableSequence;
    while ((availableSequence = dependentSequence.get()) < sequence) {
        barrier.checkAlert();
        LockSupport.parkNanos(1L);
    }

    return availableSequence;
}
 
Example #5
Source File: DisruptorQueue.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param consumerNum
 * @param threadNum
 * @param ringBufferSize RingBuffer 大小,必须是 2 的 N 次方
 */
public DisruptorQueue(int consumerNum,int threadNum,int ringBufferSize) {

    Consumer[] consumers = new Consumer[consumerNum];

    //创建ringBuffer
    ringBuffer = RingBuffer.create(ProducerType.MULTI,
            new EventFactory<RequestEvent>() {
                @Override
                public RequestEvent newInstance() {
                    return new RequestEvent();
                }
            },
            ringBufferSize ,
            new YieldingWaitStrategy());

    SequenceBarrier barriers = ringBuffer.newBarrier();

    for (int i = 0; i < consumers.length; i++) {
        consumers[i] = new Consumer();
    }

    WorkerPool<RequestEvent> workerPool = new WorkerPool<RequestEvent>(ringBuffer,
                    barriers,
                    new EventExceptionHandler(),
                    consumers);

    ringBuffer.addGatingSequences(workerPool.getWorkerSequences());
    workerPool.start(Executors.newFixedThreadPool(threadNum));

    producer = new Producer(ringBuffer);
}
 
Example #6
Source File: SpinLoopHintBusySpinWaitStrategy.java    From perf-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public long waitFor(final long sequence, Sequence cursor, final Sequence dependentSequence, final SequenceBarrier barrier)
        throws AlertException, InterruptedException
{
    long availableSequence;

    while ((availableSequence = dependentSequence.get()) < sequence)
    {
        SpinHint.spinLoopHint();
        barrier.checkAlert();
    }

    return availableSequence;
}
 
Example #7
Source File: ParkWaitStrategy.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
@Override
public long waitFor(long sequence,
                    Sequence cursor,
                    Sequence dependentSequence,
                    SequenceBarrier barrier) throws AlertException,
  InterruptedException,
  TimeoutException {
  long availableSequence;
  while ((availableSequence = dependentSequence.get()) < sequence) {
    barrier.checkAlert();
    LockSupport.parkNanos(parkFor);
  }
  return availableSequence;
}
 
Example #8
Source File: LoggerServiceImpl.java    From gflogger with Apache License 2.0 5 votes vote down vote up
public long waitFor(
	long sequence,
	Sequence cursor,
	Sequence dependentSequence,
	SequenceBarrier barrier
) throws AlertException, InterruptedException, TimeoutException {
	long availableSequence;
	if ((availableSequence = cursor.get()) < sequence) {
		flush();
		synchronized (lock) {
			++numWaiters;
			while ((availableSequence = cursor.get()) < sequence) {
				if (state == State.STOPPED) {
					disruptor.halt();
					throw AlertException.INSTANCE;
				}
				barrier.checkAlert();
				//*/
				lock.wait();
				/*/
				Thread.sleep(1);
				//*/
			}
			--numWaiters;
		}
	}
	while ((availableSequence = dependentSequence.get()) < sequence) {
		barrier.checkAlert();
	}

	return availableSequence;
}
 
Example #9
Source File: YieldWaitStrategyFactory.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
private int applyWaitMethod(final SequenceBarrier barrier, int counter)
        throws AlertException {
    // 检查中断、停止信号
    barrier.checkAlert();

    if (counter > 0) {
        --counter;
    } else {
        Thread.yield();
    }
    return counter;
}
 
Example #10
Source File: ExponentionallyIncreasingSleepingWaitStrategy.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
private int applyWaitMethod(final SequenceBarrier barrier, int currentSleep) throws AlertException {
    barrier.checkAlert();

    if (currentSleep < sleepTimeNsMax) {
        LockSupport.parkNanos(currentSleep);
        return currentSleep * 2;
    } else {
        LockSupport.parkNanos(sleepTimeNsMax);
        return currentSleep;
    }
}
 
Example #11
Source File: ExponentionallyIncreasingSleepingWaitStrategy.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public long waitFor(final long sequence, Sequence cursor, final Sequence dependentSequence, final SequenceBarrier barrier) throws AlertException {
    long availableSequence;
    int currentSleep = sleepTimeNsStart;

    while ((availableSequence = dependentSequence.get()) < sequence) {
        currentSleep = applyWaitMethod(barrier, currentSleep);
    }

    return availableSequence;
}
 
Example #12
Source File: SamplingProfiler.java    From apm-agent-java with Apache License 2.0 4 votes vote down vote up
@Override
public long waitFor(long sequence, Sequence cursor, Sequence dependentSequence, SequenceBarrier barrier) {
    return dependentSequence.get();
}
 
Example #13
Source File: RingBufferSubscriberUtils.java    From camunda-bpm-reactor with Apache License 2.0 4 votes vote down vote up
public static <T> boolean waitRequestOrTerminalEvent(
  Sequence pendingRequest,
  RingBuffer<MutableSignal<T>> ringBuffer,
  SequenceBarrier barrier,
  Subscriber<? super T> subscriber,
  AtomicBoolean isRunning
) {
  final long waitedSequence = ringBuffer.getCursor() + 1L;
  try {
    MutableSignal<T> event = null;
    while (pendingRequest.get() < 0l) {
      //pause until first request
      if (event == null) {
        barrier.waitFor(waitedSequence);
        event = ringBuffer.get(waitedSequence);

        if (event.type == MutableSignal.Type.COMPLETE) {
          try {
            subscriber.onComplete();
            return false;
          } catch (Throwable t) {
            Exceptions.throwIfFatal(t);
            subscriber.onError(t);
            return false;
          }
        } else if (event.type == MutableSignal.Type.ERROR) {
          subscriber.onError(event.error);
          return false;
        }
      } else {
        barrier.checkAlert();
      }
      LockSupport.parkNanos(1l);
    }
  } catch (TimeoutException te) {
    //ignore
  } catch (AlertException ae) {
    if (!isRunning.get()) {
      return false;
    }
  } catch (InterruptedException ie) {
    Thread.currentThread().interrupt();
  }

  return true;
}
 
Example #14
Source File: AgileWaitingStrategy.java    From camunda-bpm-reactor with Apache License 2.0 4 votes vote down vote up
@Override
public long waitFor(long sequence, Sequence cursor, Sequence dependentSequence, SequenceBarrier barrier)
  throws AlertException, InterruptedException, TimeoutException {
  return currentStrategy.waitFor(sequence, cursor, dependentSequence, barrier);
}
 
Example #15
Source File: MysqlMultiStageCoprocessor.java    From canal with Apache License 2.0 4 votes vote down vote up
@Override
public void start() {
    super.start();
    this.exception = null;
    this.disruptorMsgBuffer = RingBuffer.createSingleProducer(new MessageEventFactory(),
        ringBufferSize,
        new BlockingWaitStrategy());
    int tc = parserThreadCount > 0 ? parserThreadCount : 1;
    this.parserExecutor = Executors.newFixedThreadPool(tc, new NamedThreadFactory("MultiStageCoprocessor-Parser-"
                                                                                  + destination));

    this.stageExecutor = Executors.newFixedThreadPool(2, new NamedThreadFactory("MultiStageCoprocessor-other-"
                                                                                + destination));
    SequenceBarrier sequenceBarrier = disruptorMsgBuffer.newBarrier();
    ExceptionHandler exceptionHandler = new SimpleFatalExceptionHandler();
    // stage 2
    this.logContext = new LogContext();
    simpleParserStage = new BatchEventProcessor<MessageEvent>(disruptorMsgBuffer,
        sequenceBarrier,
        new SimpleParserStage(logContext));
    simpleParserStage.setExceptionHandler(exceptionHandler);
    disruptorMsgBuffer.addGatingSequences(simpleParserStage.getSequence());

    // stage 3
    SequenceBarrier dmlParserSequenceBarrier = disruptorMsgBuffer.newBarrier(simpleParserStage.getSequence());
    WorkHandler<MessageEvent>[] workHandlers = new DmlParserStage[tc];
    for (int i = 0; i < tc; i++) {
        workHandlers[i] = new DmlParserStage();
    }
    workerPool = new WorkerPool<MessageEvent>(disruptorMsgBuffer,
        dmlParserSequenceBarrier,
        exceptionHandler,
        workHandlers);
    Sequence[] sequence = workerPool.getWorkerSequences();
    disruptorMsgBuffer.addGatingSequences(sequence);

    // stage 4
    SequenceBarrier sinkSequenceBarrier = disruptorMsgBuffer.newBarrier(sequence);
    sinkStoreStage = new BatchEventProcessor<MessageEvent>(disruptorMsgBuffer,
        sinkSequenceBarrier,
        new SinkStoreStage());
    sinkStoreStage.setExceptionHandler(exceptionHandler);
    disruptorMsgBuffer.addGatingSequences(sinkStoreStage.getSequence());

    // start work
    stageExecutor.submit(simpleParserStage);
    stageExecutor.submit(sinkStoreStage);
    workerPool.start(parserExecutor);
}
 
Example #16
Source File: DisruptorQueueImpl.java    From jstorm with Apache License 2.0 4 votes vote down vote up
public SequenceBarrier get_barrier() {
    return _barrier;
}
 
Example #17
Source File: RingBuffer.java    From jstorm with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new SequenceBarrier to be used by an EventProcessor to track which messages are available to be read from the ring buffer given a list of
 * sequences to track.
 * 
 * @see SequenceBarrier
 * @param sequencesToTrack the additional sequences to track
 * @return A sequence barrier that will track the specified sequences.
 */
public SequenceBarrier newBarrier(Sequence... sequencesToTrack) {
    return sequencer.newBarrier(sequencesToTrack);
}