Java Code Examples for com.lmax.disruptor.dsl.ProducerType

The following examples show how to use com.lmax.disruptor.dsl.ProducerType. These examples are extracted from open source projects. 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 Project: opentelemetry-java   Source File: DisruptorEventQueue.java    License: 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 2
Source Project: swarm   Source File: DisruptorBroker.java    License: MIT License 6 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 3
Source Project: redtorch   Source File: FastEventServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	if ("BusySpinWaitStrategy".equals(waitStrategy)) {
		disruptor = new Disruptor<FastEvent>(new FastEventFactory(), 65536, DaemonThreadFactory.INSTANCE,
				ProducerType.MULTI, new BusySpinWaitStrategy());
	} else if ("SleepingWaitStrategy".equals(waitStrategy)) {
		disruptor = new Disruptor<FastEvent>(new FastEventFactory(), 65536, DaemonThreadFactory.INSTANCE,
				ProducerType.MULTI, new SleepingWaitStrategy());
	} else if ("BlockingWaitStrategy".equals(waitStrategy)) {
		disruptor = new Disruptor<FastEvent>(new FastEventFactory(), 65536, DaemonThreadFactory.INSTANCE,
				ProducerType.MULTI, new BlockingWaitStrategy());
	} else {
		disruptor = new Disruptor<FastEvent>(new FastEventFactory(), 65536, DaemonThreadFactory.INSTANCE,
				ProducerType.MULTI, new YieldingWaitStrategy());
	}
	ringBuffer = disruptor.start();
}
 
Example 4
/**
 * disruptor start.
 *
 * @param bufferSize this is disruptor buffer size.
 * @param threads this is disruptor consumer thread size.
 */
private void start(final int bufferSize, final int threads) {
    disruptor = new Disruptor<>(new TxTransactionEventFactory(), bufferSize, r -> {
        return new Thread(null, r, "disruptor-thread-" + INDEX.getAndIncrement());
    }, ProducerType.MULTI, new BlockingWaitStrategy());

    final Executor executor = new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(),
            TxTransactionThreadFactory.create("raincat-log-disruptor", false),
            new ThreadPoolExecutor.AbortPolicy());

    TxTransactionEventHandler[] consumers = new TxTransactionEventHandler[threads];
    for (int i = 0; i < threads; i++) {
        consumers[i] = new TxTransactionEventHandler(executor, txCompensationService);
    }
    disruptor.handleEventsWithWorkerPool(consumers);
    disruptor.setDefaultExceptionHandler(new IgnoreExceptionHandler());
    disruptor.start();
}
 
Example 5
Source Project: nuls   Source File: DisruptorUtil.java    License: MIT License 6 votes vote down vote up
public Disruptor<DisruptorData> createDisruptor(String name, int ringBufferSize, ThreadFactory factory) {
        if (DISRUPTOR_MAP.keySet().contains(name)) {
            throw new RuntimeException("create disruptor faild,the name is repetitive!");
        }

        Disruptor<DisruptorData> disruptor = new Disruptor<DisruptorData>(EVENT_FACTORY,
                ringBufferSize, factory, ProducerType.MULTI,
                new BlockingWaitStrategy());
        disruptor.setDefaultExceptionHandler(new NulsExceptionHandler());
        //SleepingWaitStrategy
//        disruptor.handleEventsWith(new EventHandler<DisruptorData>() {
//            @Override
//            public void onEvent(DisruptorData DisruptorData, long l, boolean b) throws Exception {
//                Log.debug(DisruptorData.getData() + "");
//            }
//        });
        DISRUPTOR_MAP.put(name, disruptor);

        return disruptor;
    }
 
Example 6
Source Project: hmily   Source File: DisruptorProviderManage.java    License: 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 7
Source Project: myth   Source File: MythTransactionEventPublisher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * start disruptor.
 *
 * @param bufferSize bufferSize
 */
private void start(final int bufferSize, final int threadSize) {
    disruptor = new Disruptor<>(new MythTransactionEventFactory(), bufferSize, runnable -> {
        return new Thread(new ThreadGroup("hmily-disruptor"), runnable,
                "disruptor-thread-" + INDEX.getAndIncrement());
    }, ProducerType.MULTI, new BlockingWaitStrategy());
    final Executor executor = new ThreadPoolExecutor(MAX_THREAD, MAX_THREAD, 0, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(),
            MythTransactionThreadFactory.create("myth-log-disruptor", false),
            new ThreadPoolExecutor.AbortPolicy());

    MythTransactionEventHandler[] consumers = new MythTransactionEventHandler[MAX_THREAD];
    for (int i = 0; i < threadSize; i++) {
        consumers[i] = new MythTransactionEventHandler(coordinatorService, executor);
    }
    disruptor.handleEventsWithWorkerPool(consumers);
    disruptor.setDefaultExceptionHandler(new IgnoreExceptionHandler());
    disruptor.start();
}
 
Example 8
Source Project: ballerina-message-broker   Source File: DbMessageStore.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
DbMessageStore(MessageDao messageDao, int bufferSize, int maxDbBatchSize) {
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("DisruptorMessageStoreThread-%d").build();

    disruptor = new Disruptor<>(DbOperation.getFactory(),
                                bufferSize, namedThreadFactory, ProducerType.MULTI, new
                                        SleepingBlockingWaitStrategy());

    disruptor.setDefaultExceptionHandler(new DbStoreExceptionHandler());

    disruptor.handleEventsWith(new DbEventMatcher(bufferSize))
             .then(new DbAccessHandler(messageDao, maxDbBatchSize))
             .then(new FinalEventHandler());
    disruptor.start();
    this.messageDao = messageDao;
}
 
Example 9
Source Project: camunda-bpm-reactor   Source File: Environment.java    License: Apache License 2.0 6 votes vote down vote up
private void initDispatcherFactoryFromConfiguration(String name) {
  if (dispatcherFactories.get(name) != null) {
    return;
  }
  for (DispatcherConfiguration dispatcherConfiguration : configuration.getDispatcherConfigurations()) {

    if (!dispatcherConfiguration.getName()
      .equalsIgnoreCase(name)) {
      continue;
    }

    if (DispatcherType.DISPATCHER_GROUP == dispatcherConfiguration.getType()) {
      addCachedDispatchers(dispatcherConfiguration.getName(),
        createDispatcherFactory(dispatcherConfiguration.getName(),
          dispatcherConfiguration.getSize() == 0 ? PROCESSORS : dispatcherConfiguration.getSize(),
          dispatcherConfiguration.getBacklog(),
          null,
          ProducerType.MULTI,
          new AgileWaitingStrategy()));
    }
  }
}
 
Example 10
Source Project: camunda-bpm-reactor   Source File: RingBufferProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private RingBufferProcessor(String name,
                            ExecutorService executor,
                            int bufferSize,
                            WaitStrategy waitStrategy,
                            boolean shared,
                            boolean autoCancel) {
  super(name, executor, autoCancel);

  this.ringBuffer = RingBuffer.create(
    shared ? ProducerType.MULTI : ProducerType.SINGLE,
    new EventFactory<MutableSignal<E>>() {
      @Override
      public MutableSignal<E> newInstance() {
        return new MutableSignal<E>();
      }
    },
    bufferSize,
    waitStrategy
  );

  this.recentSequence = new Sequence(Sequencer.INITIAL_CURSOR_VALUE);
  this.barrier = ringBuffer.newBarrier();
  //ringBuffer.addGatingSequences(recentSequence);
}
 
Example 11
private RingBufferWorkProcessor(String name,
                                ExecutorService executor,
                                int bufferSize,
                                WaitStrategy waitStrategy,
                                boolean share,
                                boolean autoCancel) {
  super(name, executor, autoCancel);

  this.ringBuffer = RingBuffer.create(
    share ? ProducerType.MULTI : ProducerType.SINGLE,
    new EventFactory<MutableSignal<E>>() {
      @Override
      public MutableSignal<E> newInstance() {
        return new MutableSignal<E>();
      }
    },
    bufferSize,
    waitStrategy
  );

  ringBuffer.addGatingSequences(workSequence);

}
 
Example 12
@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 13
@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 14
public AsyncReadResolver(int maxThreads,int bufferSize,
                         TxnSupplier txnSupplier,
                         RollForwardStatus status,
                         TrafficControl trafficControl,
                         KeyedReadResolver synchronousResolver){
    this.txnSupplier=txnSupplier;
    this.trafficControl=trafficControl;
    this.status=status;
    this.synchronousResolver = synchronousResolver;
    consumerThreads=new ThreadPoolExecutor(maxThreads,maxThreads,
            60,TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(),
            new ThreadFactoryBuilder().setNameFormat("readResolver-%d").setDaemon(true).build());

    int bSize=1;
    while(bSize<bufferSize)
        bSize<<=1;
    disruptor=new Disruptor<>(new ResolveEventFactory(),bSize,consumerThreads,
            ProducerType.MULTI,
            new BlockingWaitStrategy()); //we want low latency here, but it might cost too much in CPU
    disruptor.handleEventsWith(new ResolveEventHandler());
    ringBuffer=disruptor.getRingBuffer();
}
 
Example 15
public TransactionResolver(TxnSupplier txnSupplier, int numThreads, int bufferSize) {
     this.txnSupplier = txnSupplier;
     this.consumerThreads = MoreExecutors.namedThreadPool(numThreads, numThreads, "txn-resolve-%d", 60, true);
     this.consumerThreads.allowCoreThreadTimeOut(true);

     int bSize=1;
     while(bSize<bufferSize)
         bSize<<=1;

     disruptor = new Disruptor<>(new EventFactory<TxnResolveEvent>() {
@Override
public TxnResolveEvent newInstance() {
              return new TxnResolveEvent();
}
     },bSize,consumerThreads,
             ProducerType.MULTI,
             new BlockingWaitStrategy());
     disruptor.handleEventsWith(new ResolveEventHandler());
     ringBuffer = disruptor.getRingBuffer();
     disruptor.start();
 }
 
Example 16
Source Project: jstorm   Source File: DisruptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleProducer() throws InterruptedException {
    System.out.println("!!!!!!!!!!!!!!Begin testSingleProducer!!!!!!!!!!!!!!");
    final AtomicBoolean messageConsumed = new AtomicBoolean(false);

    // Set queue length to 1, so that the RingBuffer can be easily full
    // to trigger consumer blocking
    DisruptorQueue queue = createQueue("consumerHang", ProducerType.SINGLE, 1);
    push(queue, 1);
    Runnable producer = new Producer(queue);
    Runnable consumer = new Consumer(queue, new EventHandler<Object>() {
        long count = 0;

        @Override
        public void onEvent(Object obj, long sequence, boolean endOfBatch) throws Exception {

            messageConsumed.set(true);
            System.out.println("Consume " + count++);
        }
    });

    run(producer, 0, 0, consumer, 50);
    Assert.assertTrue("disruptor message is never consumed due to consumer thread hangs", messageConsumed.get());

    System.out.println("!!!!!!!!!!!!!!End testSingleProducer!!!!!!!!!!!!!!");
}
 
Example 17
Source Project: sofa-jraft   Source File: FSMCallerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean init(final FSMCallerOptions opts) {
    this.logManager = opts.getLogManager();
    this.fsm = opts.getFsm();
    this.closureQueue = opts.getClosureQueue();
    this.afterShutdown = opts.getAfterShutdown();
    this.node = opts.getNode();
    this.nodeMetrics = this.node.getNodeMetrics();
    this.lastAppliedIndex.set(opts.getBootstrapId().getIndex());
    notifyLastAppliedIndexUpdated(this.lastAppliedIndex.get());
    this.lastAppliedTerm = opts.getBootstrapId().getTerm();
    this.disruptor = DisruptorBuilder.<ApplyTask> newInstance() //
        .setEventFactory(new ApplyTaskFactory()) //
        .setRingBufferSize(opts.getDisruptorBufferSize()) //
        .setThreadFactory(new NamedThreadFactory("JRaft-FSMCaller-Disruptor-", true)) //
        .setProducerType(ProducerType.MULTI) //
        .setWaitStrategy(new BlockingWaitStrategy()) //
        .build();
    this.disruptor.handleEventsWith(new ApplyTaskHandler());
    this.disruptor.setDefaultExceptionHandler(new LogExceptionHandler<Object>(getClass().getSimpleName()));
    this.taskQueue = this.disruptor.start();
    if (this.nodeMetrics.getMetricRegistry() != null) {
        this.nodeMetrics.getMetricRegistry().register("jraft-fsm-caller-disruptor",
            new DisruptorMetricSet(this.taskQueue));
    }
    this.error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_NONE);
    LOG.info("Starts FSMCaller successfully.");
    return true;
}
 
Example 18
Source Project: sofa-jraft   Source File: ReadOnlyServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean init(final ReadOnlyServiceOptions opts) {
    this.node = opts.getNode();
    this.nodeMetrics = this.node.getNodeMetrics();
    this.fsmCaller = opts.getFsmCaller();
    this.raftOptions = opts.getRaftOptions();

    this.scheduledExecutorService = Executors
        .newSingleThreadScheduledExecutor(new NamedThreadFactory("ReadOnlyService-PendingNotify-Scanner", true));
    this.readIndexDisruptor = DisruptorBuilder.<ReadIndexEvent> newInstance() //
        .setEventFactory(new ReadIndexEventFactory()) //
        .setRingBufferSize(this.raftOptions.getDisruptorBufferSize()) //
        .setThreadFactory(new NamedThreadFactory("JRaft-ReadOnlyService-Disruptor-", true)) //
        .setWaitStrategy(new BlockingWaitStrategy()) //
        .setProducerType(ProducerType.MULTI) //
        .build();
    this.readIndexDisruptor.handleEventsWith(new ReadIndexEventHandler());
    this.readIndexDisruptor
        .setDefaultExceptionHandler(new LogExceptionHandler<Object>(getClass().getSimpleName()));
    this.readIndexQueue = this.readIndexDisruptor.start();
    if (this.nodeMetrics.getMetricRegistry() != null) {
        this.nodeMetrics.getMetricRegistry() //
            .register("jraft-read-only-service-disruptor", new DisruptorMetricSet(this.readIndexQueue));
    }
    // listen on lastAppliedLogIndex change events.
    this.fsmCaller.addLastAppliedLogIndexListener(this);

    // start scanner
    this.scheduledExecutorService.scheduleAtFixedRate(() -> onApplied(this.fsmCaller.getLastAppliedIndex()),
        this.raftOptions.getMaxElectionDelayMs(), this.raftOptions.getMaxElectionDelayMs(), TimeUnit.MILLISECONDS);
    return true;
}
 
Example 19
Source Project: youkefu   Source File: DisruptorConfigure.java    License: 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 20
Source Project: netty-pubsub   Source File: RingBufferWorkerPoolFactory.java    License: MIT License 5 votes vote down vote up
/**
 * 
 * @param type  ����������  �������� ��������
 * @param bufferSize  ringbuffer������
 * @param waitStrategy   �ȴ�����
 * @param messageConsumers  ������
 */
@SuppressWarnings("unchecked")
public void initAndStart(ProducerType type, int bufferSize, WaitStrategy waitStrategy, MessageConsumer[] messageConsumers) {
	if(!startFlag){
	//1. ����ringBuffer����
	this.ringBuffer = RingBuffer.create(type,
			new EventFactory<MessageWrapper>() {
				public MessageWrapper newInstance() {
					return new MessageWrapper();
				}
			},
			bufferSize,
			waitStrategy);
	//2.�������դ��
	this.sequenceBarrier = this.ringBuffer.newBarrier();
	//3.���ù�����
	this.workerPool = new WorkerPool(this.ringBuffer,
			this.sequenceBarrier, 
			new EventExceptionHandler(), messageConsumers);
	//4 �����������������������
	for(MessageConsumer mc : messageConsumers){
		this.consumers.put(mc.getConsumerId(), mc);
	}
	//5 ������ǵ�sequences
	this.ringBuffer.addGatingSequences(this.workerPool.getWorkerSequences());
	//6 �������ǵĹ�����
	this.workerPool.start(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()/2));
	//7.����������־����ֹ�ظ�����
	startFlag=true;
	}
}
 
Example 21
Source Project: match-trade   Source File: DisruptorConfig.java    License: 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 22
Source Project: litchi   Source File: MessageThread.java    License: Apache License 2.0 5 votes vote down vote up
public MessageThread(String threadName, int bufferSize, EventHandler<MessageBuffer> handler, WaitStrategy waitStrategy) {
    this.disruptor = new Disruptor<>(
            () -> new MessageBuffer(),
            bufferSize,
            new NamedThreadFactory(threadName),
            ProducerType.MULTI,
            waitStrategy
    );

    disruptor.handleEventsWith(handler);
    disruptor.setDefaultExceptionHandler(new ErrorHandler<>());
}
 
Example 23
Source Project: conga   Source File: RingBufferSupplier.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts a background thread to process events
 */
public void start() {
  if (disruptor == null) {
    disruptor = new Disruptor<BufferEvent>(BufferEvent::new, queueDepth, threadFactory,
        ProducerType.SINGLE, new BusySpinWaitStrategy());

    // Connect the handler
    disruptor.handleEventsWith(eventHandler);

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

    ringBuffer = disruptor.getRingBuffer();
  }
}
 
Example 24
Source Project: fast-family-master   Source File: LogEventPublisher.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
    disruptor = new Disruptor<LogEvent>(new LogEventFactory(), 1024, r -> {
        AtomicInteger integer = new AtomicInteger(1);
        return new Thread(null, r, "disruptor-thread-" + integer.getAndIncrement());
    }, ProducerType.MULTI, new BlockingWaitStrategy());
    disruptor.handleEventsWithWorkerPool(new LogEventHandler(logRepository));
    disruptor.setDefaultExceptionHandler(new IgnoreExceptionHandler());
    disruptor.start();
}
 
Example 25
Source Project: java-concurrent-programming   Source File: Main.java    License: 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 26
Source Project: java-trader   Source File: AsyncEventServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(BeansContainer beansContainer) throws Exception {
    //启动disruptor
    disruptor = new Disruptor<AsyncEvent>( new AsyncEventFactory()
        , ConfigUtil.getInt(ITEM_DISRUPTOR_RINGBUFFER_SIZE, 65536)
        , executorService
        , ProducerType.MULTI
        , ConcurrentUtil.createDisruptorWaitStrategy(ConfigUtil.getString(ITEM_DISRUPTOR_WAIT_STRATEGY))
        );
}
 
Example 27
Source Project: java-trader   Source File: TradletGroupEngine.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(BeansContainer beansContainer) {
    super.init(beansContainer);

    ExecutorService executorService = beansContainer.getBean(ExecutorService.class);

    //读取Group特有配置, 如果不存在, 读取通用配置
    String ringBufferSizeStr = ConfigUtil.getString(TradletServiceImpl.ITEM_TRADLETGROUP+"#"+group.getId()+TradletServiceImpl.ITEM_SUFFIX_DISRUPTOR_RINGBUFFER_SIZE);
    if ( StringUtil.isEmpty(ringBufferSizeStr)) {
        ringBufferSizeStr = ConfigUtil.getString(TradletServiceImpl.ITEM_GLOBAL_DISRUPTOR_RINGBUFFER_SIZE);
    }
    String disruptorWaitStrategy = ConfigUtil.getString(TradletServiceImpl.ITEM_TRADLETGROUP+"#"+group.getId()+TradletServiceImpl.ITEM_SUFFIX_DISRUPTOR_WAIT_STRATEGY);
    if ( StringUtil.isEmpty(disruptorWaitStrategy)) {
        disruptorWaitStrategy = ConfigUtil.getString(TradletServiceImpl.ITEM_GLOBAL_DISRUPTOR_WAIT_STRATEGY);
    }
    int ringBufferSize = 4096;
    if ( !StringUtil.isEmpty(ringBufferSizeStr)) {
        ringBufferSize = ConversionUtil.toInt(ringBufferSizeStr);
    }
    disruptor = new Disruptor<TradletEvent>( new TradletEventFactory()
        , ringBufferSize
        , executorService
        , ProducerType.MULTI
        , ConcurrentUtil.createDisruptorWaitStrategy(disruptorWaitStrategy)
        );
    disruptor.handleEventsWith(this);
    ringBuffer = disruptor.start();

}
 
Example 28
Source Project: product-microgateway   Source File: DataEndpointGroup.java    License: Apache License 2.0 5 votes vote down vote up
EventQueue(int queueSize) {
    eventQueuePool = Executors.newCachedThreadPool(
            new DataBridgeThreadFactory("EventQueue"));
    eventQueueDisruptor = new Disruptor<>(new WrappedEventFactory(), queueSize, eventQueuePool,
            ProducerType.MULTI, new BlockingWaitStrategy());
    eventQueueDisruptor.handleEventsWith(new EventQueueWorker());
    this.ringBuffer = eventQueueDisruptor.start();
}
 
Example 29
Source Project: NetDiscovery   Source File: DisruptorQueue.java    License: 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 30
Source Project: gridgo   Source File: DisruptorWorkerPoolExecutionStrategy.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public DisruptorWorkerPoolExecutionStrategy(ProducerType type, final int bufferSize, final int numWorkers,
        final WaitStrategy waitStrategy, final ThreadFactory threadFactory) {
    this.disruptor = new Disruptor<>(ExecutionContextEvent::new, bufferSize, threadFactory, type, waitStrategy);
    WorkHandler<ExecutionContextEvent<T, H>>[] workers = new WorkHandler[numWorkers];
    for (int i = 0; i < numWorkers; i++) {
        workers[i] = event -> {
            event.getContext().execute();
        };
    }
    this.disruptor.handleEventsWithWorkerPool(workers);
}