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

The following examples show how to use com.lmax.disruptor.dsl.Disruptor#start() . 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: DisruptorProviderManage.java    From hmily with Apache License 2.0 6 votes vote down vote up
/**
 * start disruptor.
 */
@SuppressWarnings("unchecked")
public void startup() {
    Disruptor<DataEvent<T>> disruptor = new Disruptor<>(new DisruptorEventFactory<>(),
            size,
            HmilyThreadFactory.create("disruptor_consumer_" + consumerFactory.fixName(), false),
            ProducerType.MULTI,
            new BlockingWaitStrategy());
    DisruptorConsumer<T>[] consumers = new DisruptorConsumer[consumerSize];
    for (int i = 0; i < consumerSize; i++) {
        consumers[i] = new DisruptorConsumer<>(consumerFactory);
    }
    disruptor.handleEventsWithWorkerPool(consumers);
    disruptor.setDefaultExceptionHandler(new IgnoreExceptionHandler());
    disruptor.start();
    RingBuffer<DataEvent<T>> ringBuffer = disruptor.getRingBuffer();
    provider = new DisruptorProvider<>(ringBuffer);
}
 
Example 4
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 5
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 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: 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 8
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 9
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 10
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 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: 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 13
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 14
Source File: DisruptorBroker.java    From swarm with MIT License 5 votes vote down vote up
public void initialize() throws Exception {
  logger.info("Initializing...");
  logger.info("> parallelism={}", builder.parallelism);
  logger.info("> lowLatency={}", builder.lowLatency);
  logger.info("> bufferSize={}", builder.bufferSize);

  WaitStrategy waitStrategy =
      builder.isLowLatency() ? new BusySpinWaitStrategy() : new BlockingWaitStrategy();
  ProducerType producerType =
      builder.getProducerMode() == ProducerMode.SINGLE ? ProducerType.SINGLE : ProducerType.MULTI;
  EventFactory eventFactory = () -> new Event();

  disruptor =
      new Disruptor(
          eventFactory, builder.bufferSize, getThreadFactory(), producerType, waitStrategy);
  initializeRingBuffer();

  disruptor.handleEventsWithWorkerPool(getWorkersPool());
  // Start the Disruptor, starts all threads running
  disruptor.start();

  logger.info("Initialized");
}
 
Example 15
Source File: Main.java    From java-concurrent-programming with MIT License 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    Executor executor = Executors.newCachedThreadPool();
    PCDataFactory factory = new PCDataFactory();

    int bufferSize = 1024;
    Disruptor<PCData> disruptor = new Disruptor<PCData>(factory,
            bufferSize,
            executor,
            ProducerType.MULTI,
            new BlockingWaitStrategy()
            );
    disruptor.handleEventsWithWorkerPool(
            new Consumer(),
            new Consumer(),
            new Consumer(),
            new Consumer()
    );
    disruptor.start();

    // 1个生产者 4个消费者
    RingBuffer<PCData> ringBuffer = disruptor.getRingBuffer();
    Producer producer = new Producer(ringBuffer);
    ByteBuffer bb = ByteBuffer.allocate(8);
    for (long l = 0; true; l++) {
        bb.putLong(0, l);
        producer.pushData(bb);
        Thread.sleep(100);
        System.out.println("add data "+l);
    }
}
 
Example 16
Source File: DisruptorConfig.java    From match-trade with Apache License 2.0 5 votes vote down vote up
@Bean
public RingBuffer<MatchOrder> ringBuffer() {
	EventFactory<MatchOrder> factory = new OrderFactory();
	int ringBufferSize = 1024 * 1024;
	ThreadFactory disruptorThreadPool = new ThreadFactoryBuilder().setNameFormat("DisruptorThreadPool").build();
	Disruptor<MatchOrder> disruptor = new Disruptor<MatchOrder>(factory, ringBufferSize, disruptorThreadPool,
			ProducerType.MULTI, new YieldingWaitStrategy());
	disruptor.setDefaultExceptionHandler(new MyHandlerException());// Disruptor异常统计
	// 单线处理撮合, 并行处理盘口和订单薄
	disruptor.handleEventsWithWorkerPool(new MatchHandler(),new MatchHandler()).then(new InputDepthHandler(),new OutDepthHandler());
	disruptor.start();
	return disruptor.getRingBuffer();
}
 
Example 17
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 18
Source File: LongEventMain.java    From util4j with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception
    {
    	final Logger log=LoggerFactory.getLogger("");
        // Executor that will be used to construct new threads for consumers
        Executor executor = new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>(),new NamedThreadFactory("disruptor"));

        // The factory for the event
        LongEventFactory factory = new LongEventFactory();

        // Specify the size of the ring buffer, must be power of 2.
        int bufferSize = 1024;

        // Construct the Disruptor
        final Disruptor<LongEvent<Runnable>> disruptor = new Disruptor<>(factory, bufferSize, executor);

        //注册消费者
        // Connect the handler
//        disruptor.handleEventsWith(new LongEventHandler("消费者A"),new LongEventHandler("消费者B"));
        disruptor.handleEventsWithWorkerPool(new LongEventWorkHandler("消费者C"),new LongEventWorkHandler("消费者D"));
        // Start the Disruptor, starts all threads running
        disruptor.start();
        final AtomicLong seq=new AtomicLong();
        //生产者1
        new Thread(new Runnable() {
			@Override
			public void run() {
				// Get the ring buffer from the Disruptor to be used for publishing.
				RingBuffer<LongEvent<Runnable>> ringBuffer = disruptor.getRingBuffer();
				LongEventProducer producer = new LongEventProducer(ringBuffer);
		        for (long l = 0; true; l++)
		        {
		            producer.publish(new Task("task:"+seq.incrementAndGet()));
		            try {
						Thread.sleep(RandomUtils.nextInt(1000));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
		        }
			}
		}).start();
    }
 
Example 19
Source File: DisruptorUtil.java    From nuls with MIT License 4 votes vote down vote up
public void start(String name) {
    Disruptor<DisruptorData> disruptor = DISRUPTOR_MAP.get(name);
    AssertUtil.canNotEmpty(disruptor, "the disruptor is not exist!name:" + name);
    disruptor.start();
}