Java Code Examples for com.lmax.disruptor.dsl.Disruptor#handleEventsWith()

The following examples show how to use com.lmax.disruptor.dsl.Disruptor#handleEventsWith() . 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: DisruptorLogAppenderBase.java    From High-concurrent-server with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void start() {
	if (appenderCount == 0) {
		addError("No attached appenders found.");
		return;
	}
	if (queueSize < 1) {
		addError("Invalid queue size [" + queueSize + "]");
		return;
	}
	addInfo("环形缓冲区的大小: " + queueSize);
	Executor executor = Executors.newCachedThreadPool();
	Disruptor<LogValueEvent> disruptor = new Disruptor<LogValueEvent>(
			LogValueEvent.EVENT_FACTORY, queueSize, executor,
			ProducerType.MULTI, new SleepingWaitStrategy());
	disruptor.handleEventsWith(new LogDisruptorEventHandle());
	disruptor.start();
	ringBuffer = disruptor.getRingBuffer();
	super.start();
}
 
Example 2
Source File: DisruptorEventQueue.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
DisruptorEventQueue(
    int bufferSize, WaitStrategy waitStrategy, SpanProcessor spanProcessor, boolean blocking) {
  // Create new Disruptor for processing. Note that Disruptor creates a single thread per
  // consumer (see https://github.com/LMAX-Exchange/disruptor/issues/121 for details);
  // this ensures that the event handler can take unsynchronized actions whenever possible.
  Disruptor<DisruptorEvent> disruptor =
      new Disruptor<>(
          EVENT_FACTORY,
          bufferSize,
          new DaemonThreadFactory(WORKER_THREAD_NAME),
          ProducerType.MULTI,
          waitStrategy);
  disruptor.handleEventsWith(new DisruptorEventHandler(spanProcessor));
  this.ringBuffer = disruptor.start();
  this.blocking = blocking;
}
 
Example 3
Source File: DisruptorExample.java    From pragmatic-java-engineer with GNU General Public License v3.0 6 votes vote down vote up
public void test() throws Exception {
    TestEventFactory factory = new TestEventFactory();

    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    Disruptor<TestEvent> disruptor = new Disruptor<>(factory, 1024, threadFactory);

    disruptor.handleEventsWith(new TestEventHandler());

    disruptor.start();

    RingBuffer<TestEvent> ringBuffer = disruptor.getRingBuffer();

    TestEventProducerWithTranslator producer = new TestEventProducerWithTranslator(ringBuffer);

    ByteBuffer bb = ByteBuffer.allocate(8);
    for (long l = 0; true; l++) {
        bb.putLong(0, l);
        producer.onData(bb);
        Thread.sleep(1000);
    }
}
 
Example 4
Source File: LongEventMain.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        Executor executor = Executors.newCachedThreadPool();

        LongEventFactory eventFactory = new LongEventFactory();
        int bufferSize = 1024;

//        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(eventFactory, bufferSize, executor);
//        disruptor.handleEventsWith(new LongEventHandler());
//        disruptor.start();

        Disruptor<LongEvent> disruptor = new Disruptor<>(LongEvent::new, bufferSize, executor);
        disruptor.handleEventsWith((event, sequence, endOfBatch) -> {System.out.println("Event: " + event);
            System.out.println("CurrentThreadName:" + Thread.currentThread().getName());
        });
        disruptor.start();

        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
        LongEventProducer producer = new LongEventProducer(ringBuffer);

        ByteBuffer bb = ByteBuffer.allocate(8);
        for (long l = 0; true; l++) {
            bb.putLong(0, l);
            ringBuffer.publishEvent((event, sequence, buffer) -> event.set(buffer.getLong(0)), bb);

           // producer.onData(bb);
            //Thread.sleep(1000);
        }
    }
 
Example 5
Source File: Source.java    From cep with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Create a new source.
 * <p>This method will prepare the instance with some needed variables
 * in order to be started later with the start method (implemented by children).
 *
 * @param parsersManager Instance of ParserManager that will serve parsers to this source instance
 * @param eventHandler Instance of EventHandler that will receive the events generated by this source instance
 * @param properties Map of properties associated with this source
 */

public Source(ParsersManager parsersManager, EventHandler eventHandler, Map<String, Object> properties) {
    // Save the references for later use
    this.parsersManager = parsersManager;
    this.properties = properties;

    // Create the ring buffer for this topic and start it
    Disruptor<MapEvent> disruptor = new Disruptor<>(new MapEventFactory(), ConfigData.getRingBufferSize(), Executors.newCachedThreadPool());
    disruptor.handleEventsWith(eventHandler);
    disruptor.start();

    // Create the event producer that will receive the events produced by
    // this source instance
    eventProducer = new EventProducer(disruptor.getRingBuffer());
    prepare();
}
 
Example 6
Source File: DisruptorLogAppenderBase.java    From NettyFileTransfer with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void start() {
	if (appenderCount == 0) {
		addError("No attached appenders found.");
		return;
	}
	if (queueSize < 1) {
		addError("Invalid queue size [" + queueSize + "]");
		return;
	}
	addInfo("环形缓冲区的大小: " + queueSize);
	Executor executor = Executors.newCachedThreadPool();
	Disruptor<LogValueEvent> disruptor = new Disruptor<LogValueEvent>(
			LogValueEvent.EVENT_FACTORY, queueSize, executor,
			ProducerType.MULTI, new SleepingWaitStrategy());
	disruptor.handleEventsWith(new LogDisruptorEventHandle());
	disruptor.start();
	ringBuffer = disruptor.getRingBuffer();
	super.start();
}
 
Example 7
Source File: DisruptorConfigure.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "deprecation" })
@Bean(name="multiupdate")   
   public Disruptor<UserDataEvent> multiupdate() {   
   	Executor executor = Executors.newCachedThreadPool();
   	 MultiUpdateEventFactory factory = new MultiUpdateEventFactory();
   	 Disruptor<UserDataEvent> disruptor = new Disruptor<UserDataEvent>(factory, 1024, executor, ProducerType.MULTI , new BlockingWaitStrategy());
   	 disruptor.handleEventsWith(new MultiUpdateEventHandler());
   	 disruptor.setDefaultExceptionHandler(new UKeFuExceptionHandler());
   	 disruptor.start();
        return disruptor;   
   }
 
Example 8
Source File: DisruptorJmsMessageSenderFactory.java    From artemis-disruptor-miaosha with Apache License 2.0 5 votes vote down vote up
/**
 * 得到返回的结果后, 必须执行 {@link DisruptorJmsMessageSender#getDisruptor()}.start() 才可以使用
 *
 * @param session
 * @param messageProducer
 * @param dupMessageDetectStrategy
 * @param ringBufferSize           必须是2的次方
 * @return
 * @throws JMSException
 */
public static DisruptorJmsMessageSender create(
    Session session,
    MessageProducer messageProducer,
    DupMessageDetectStrategy dupMessageDetectStrategy,
    int ringBufferSize
) throws JMSException {

  Disruptor<PayloadEvent> disruptor = new Disruptor<>(
      PayloadEvent::new,
      ringBufferSize,
      Executors.defaultThreadFactory()
  );

  PayloadEventProducer payloadEventProducer = new PayloadEventProducer(disruptor.getRingBuffer());

  DisruptorJmsMessageSender messageSender = new DisruptorJmsMessageSender();
  messageSender.setSession(session);
  messageSender.setMessageProducer(messageProducer);
  messageSender.setPayloadEventProducer(payloadEventProducer);
  if (dupMessageDetectStrategy != null) {
    messageSender.setDupMessageDetectStrategy(dupMessageDetectStrategy);
  }

  disruptor.handleEventsWith(messageSender);

  messageSender.setDisruptor(disruptor);

  return messageSender;

}
 
Example 9
Source File: DisruptorEventQueue.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static DisruptorEventQueue create() {
  // Create new Disruptor for processing. Note that Disruptor creates a single thread per
  // consumer (see https://github.com/LMAX-Exchange/disruptor/issues/121 for details);
  // this ensures that the event handler can take unsynchronized actions whenever possible.
  Disruptor<DisruptorEvent> disruptor =
      new Disruptor<>(
          DisruptorEventFactory.INSTANCE,
          DISRUPTOR_BUFFER_SIZE,
          new DaemonThreadFactory("OpenCensus.Disruptor"),
          ProducerType.MULTI,
          new SleepingWaitStrategy(0, 1000 * 1000));
  disruptor.handleEventsWith(new DisruptorEventHandler[] {DisruptorEventHandler.INSTANCE});
  disruptor.start();
  final RingBuffer<DisruptorEvent> ringBuffer = disruptor.getRingBuffer();

  DisruptorEnqueuer enqueuer =
      new DisruptorEnqueuer() {
        @Override
        public void enqueue(Entry entry) {
          long sequence = ringBuffer.next();
          try {
            DisruptorEvent event = ringBuffer.get(sequence);
            event.setEntry(entry);
          } finally {
            ringBuffer.publish(sequence);
          }
        }
      };
  return new DisruptorEventQueue(disruptor, enqueuer);
}
 
Example 10
Source File: DisruptorAdapterHandler.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
        protected Disruptor<ConcurrentEvent> initialValue() {
            Disruptor<ConcurrentEvent> disruptor = new Disruptor<>(
                    ConcurrentEventFactory.DEFAULT, DEFAULT_RING_BUFFER_SIZE, CACHED_THREAD_POOL, ProducerType.SINGLE, new BlockingWaitStrategy());
            disruptor.handleEventsWith(new ConcurrentHandler());
//            disruptor.handleExceptionsWith();
            disruptor.start();
            return disruptor;
        }
 
Example 11
Source File: DisruptorAdapterBy41xHandler.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
        protected Disruptor<ConcurrentEvent> initialValue() {
            Disruptor<ConcurrentEvent> disruptor = new Disruptor<>(
                    ConcurrentEventFactory.DEFAULT, DEFAULT_RING_BUFFER_SIZE, CACHED_THREAD_POOL, ProducerType.SINGLE, new LiteBlockingWaitStrategy());
            disruptor.handleEventsWith(new ConcurrentHandler());
//            disruptor.handleExceptionsWith();
            disruptor.start();
            return disruptor;
        }
 
Example 12
Source File: BenchmarkHandler.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
        protected Disruptor<ConcurrentEvent> initialValue() {
            Disruptor<ConcurrentEvent> disruptor = new Disruptor<>(
                    ConcurrentEventFactory.DEFAULT, DEFAULT_RING_BUFFER_SIZE, CACHED_THREAD_POOL, ProducerType.SINGLE, new LiteBlockingWaitStrategy());
            disruptor.handleEventsWith(new ConcurrentHandler());
//            disruptor.handleExceptionsWith();
            disruptor.start();
            return disruptor;
        }
 
Example 13
Source File: ThreadBoundExecutorImpl.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
public ThreadBoundExecutorImpl(ThreadBoundEventProcessor eventProcessor, int bufferSize, ThreadFactory threadFactory, int workers) {
    this.threadFactory = threadFactory;
    this.disruptors = new ArrayList<>(workers);

    logger.info("Initializing (Disruptor)ThreadBoundExecutor[{}]",threadFactory);
    ThreadBoundEventWrapperFactory eventFactory = new ThreadBoundEventWrapperFactory();

    for (int i = 0; i < workers; i++) {
        Disruptor<ThreadBoundEventWrapper> disruptor = new Disruptor<>(eventFactory,bufferSize,threadFactory);
        disruptor.handleEventsWith(new ThreadBoundEventHandler(eventProcessor, bufferSize));
        this.disruptors.add(disruptor);
        disruptor.start();
    }
}
 
Example 14
Source File: DisruptorUtil.java    From nuls with MIT License 4 votes vote down vote up
public EventHandlerGroup<T> handleEventWith(String name, EventHandler<T> eventHandler) {
    Disruptor disruptor = DISRUPTOR_MAP.get(name);
    AssertUtil.canNotEmpty(disruptor, "the disruptor is not exist!name:" + name);
    return disruptor.handleEventsWith(eventHandler);
}
 
Example 15
Source File: AppMain.java    From perf-workshop with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception
{
    final CommandLineArgs commandLineArgs = new CommandLineArgs();
    new JCommander(commandLineArgs).parse(args);

    final Disruptor<Packet> packetDisruptor =
            new Disruptor<>(new Packet.Factory(commandLineArgs.getRecordLength()), commandLineArgs.getBufferSize(),
                    newCachedThreadPool(DAEMON_THREAD_FACTORY), ProducerType.SINGLE, new SpinLoopHintBusySpinWaitStrategy());

    final Overrides overrides = new Overrides(commandLineArgs);
    overrides.init();

    final Journaller journaller = new Journaller(SYSTEM_NANO_TIMER, commandLineArgs, overrides.enableJournaller());
    journaller.init();

    final Histogram[] messageTransitTimeHistograms = new Histogram[commandLineArgs.getNumberOfIterations()];
    setAll(messageTransitTimeHistograms, HISTOGRAMS::createHistogramForArray);
    final Histogram[] interMessageTimeHistograms = new Histogram[commandLineArgs.getNumberOfIterations()];
    setAll(interMessageTimeHistograms, HISTOGRAMS::createHistogramForArray);

    packetDisruptor.handleEventsWith(
            runOnCpus(wrap(new Accumulator(messageTransitTimeHistograms, interMessageTimeHistograms, SYSTEM_NANO_TIMER, commandLineArgs)::process),
                    "Accumulator", overrides.getAccumulatorThreadAffinity()),
            runOnCpus(wrap(journaller::process), "Journaller", overrides.getJournallerThreadAffinity()));

    packetDisruptor.start();

    final InputReader inputReader = new InputReader(packetDisruptor.getRingBuffer(), SYSTEM_NANO_TIMER, commandLineArgs);

    if(commandLineArgs.runSpinners())
    {
        System.out.println("Starting spinner threads to perturb the system");
        Spinners.SPINNERS.start();
    }

    System.out.println("Starting replay at " + new Date());

    final Thread thread = DAEMON_THREAD_FACTORY.newThread(THREADS.runOnCpu(inputReader::processFiles,
            overrides.getProducerThreadAffinity()));
    thread.start();

    try
    {
        thread.join();
        System.out.println("Finished replay at " + new Date());
        packetDisruptor.shutdown(1, TimeUnit.MINUTES);
    }
    catch (TimeoutException e)
    {
        throw new RuntimeException("Consumers did not process remaining events within timeout", e);
    }
    finally
    {
        Spinners.SPINNERS.stop();
        packetDisruptor.halt();
    }

    System.out.println("Pausing for 10 seconds...");
    THREADS.sleep(10L, TimeUnit.SECONDS);
}
 
Example 16
Source File: OutputSubscriber.java    From flink-spector with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor
 *
 * @param instance  id of paired sink
 * @param disruptor disruptor transporting the messages
 */
public OutputSubscriber(int instance, Disruptor<OutputEvent> disruptor) {
    this.instance = instance;
    disruptor.handleEventsWith(new ByteEventHandler());
}