Java Code Examples for com.lmax.disruptor.EventFactory

The following examples show how to use com.lmax.disruptor.EventFactory. 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: 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 2
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 3
@Before
@SuppressWarnings("unchecked")
public void setup() {
    responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() {
        @Override
        public ResponseEvent newInstance() {
            return new ResponseEvent();
        }
    }, 1024, Executors.newCachedThreadPool());

    firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>());
    latch = new CountDownLatch(1);
    responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() {
        @Override
        public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
            firedEvents.add(event.getMessage());
            latch.countDown();
        }
    });
    responseRingBuffer = responseBuffer.start();
}
 
Example 4
Source Project: jstorm   Source File: RingBuffer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Construct a RingBuffer with the full option set.
 * 
 * @param eventFactory to newInstance entries for filling the RingBuffer
 * @param sequencer sequencer to handle the ordering of events moving through the RingBuffer.
 * @throws IllegalArgumentException if bufferSize is less than 1 or not a power of 2
 */
public RingBuffer(EventFactory<E> eventFactory, Sequencer sequencer) {
    this.sequencer = sequencer;
    this.bufferSize = sequencer.getBufferSize();

    if (bufferSize < 1) {
        throw new IllegalArgumentException("bufferSize must not be less than 1");
    }
    if (Integer.bitCount(bufferSize) != 1) {
        throw new IllegalArgumentException("bufferSize must be a power of 2");
    }

    this.indexMask = bufferSize - 1;
    this.entries = new Object[sequencer.getBufferSize()];
    fill(eventFactory);
}
 
Example 5
Source Project: sofa-jraft   Source File: DefaultRheaKVStore.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Batching(EventFactory<T> factory, int bufSize, String name, EventHandler<T> handler) {
    this.name = name;
    this.disruptor = new Disruptor<>(factory, bufSize, new NamedThreadFactory(name, true));
    this.disruptor.handleEventsWith(handler);
    this.disruptor.setDefaultExceptionHandler(new LogExceptionHandler<Object>(name));
    this.ringBuffer = this.disruptor.start();
}
 
Example 6
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 7
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 8
Source Project: apm-agent-java   Source File: SamplingProfiler.java    License: Apache License 2.0 5 votes vote down vote up
private RingBuffer<ActivationEvent> createRingBuffer() {
    return RingBuffer.<ActivationEvent>createMultiProducer(
        new EventFactory<ActivationEvent>() {
            @Override
            public ActivationEvent newInstance() {
                return new ActivationEvent();
            }
        },
        RING_BUFFER_SIZE,
        new NoWaitStrategy());
}
 
Example 9
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 10
Source Project: Okra   Source File: LogicProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public LogicProcessor(EventFactory<ConcurrentEvent> factory, EventHandler<ConcurrentEvent> handler, int rbSize, ExecutorService es, ProducerType pt, WaitStrategy ws) {
    this.disruptor = new Disruptor<>(factory, rbSize, es, pt, ws);
    this.disruptor.handleEventsWith(handler);
    //  disruptor.handleExceptionsWith();
    this.disruptor.start();
    this.msgQueue = newQueue();
}
 
Example 11
Source Project: couchbase-jvm-core   Source File: ViewHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setup() {
    responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() {
        @Override
        public ResponseEvent newInstance() {
            return new ResponseEvent();
        }
    }, 1024, Executors.newCachedThreadPool());

    firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>());
    latch = new CountDownLatch(1);
    responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() {
        @Override
        public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
            firedEvents.add(event.getMessage());
            latch.countDown();
        }
    });
    responseRingBuffer = responseBuffer.start();

    CoreEnvironment environment = mock(CoreEnvironment.class);
    when(environment.scheduler()).thenReturn(Schedulers.computation());
    when(environment.maxRequestLifetime()).thenReturn(10000L); // 10 seconds
    when(environment.autoreleaseAfter()).thenReturn(2000L);
    when(environment.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);
    endpoint = mock(AbstractEndpoint.class);
    when(endpoint.environment()).thenReturn(environment);
    when(endpoint.context()).thenReturn(new CoreContext(environment, null, 1));
    when(environment.userAgent()).thenReturn("Couchbase Client Mock");

    queue = new ArrayDeque<ViewRequest>();
    handler = new ViewHandler(endpoint, responseRingBuffer, queue, false, false);
    channel = new EmbeddedChannel(handler);
}
 
Example 12
Source Project: couchbase-jvm-core   Source File: QueryHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void commonSetup() {
    responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() {
        @Override
        public ResponseEvent newInstance() {
            return new ResponseEvent();
        }
    }, 1024, Executors.newCachedThreadPool());

    firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>());
    latch = new CountDownLatch(1);
    responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() {
        @Override
        public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
            firedEvents.add(event.getMessage());
            latch.countDown();
        }
    });
    responseRingBuffer = responseBuffer.start();

    CoreEnvironment environment = mock(CoreEnvironment.class);
    when(environment.scheduler()).thenReturn(Schedulers.computation());
    when(environment.maxRequestLifetime()).thenReturn(10000L);
    when(environment.autoreleaseAfter()).thenReturn(2000L);
    when(environment.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);
    endpoint = mock(AbstractEndpoint.class);
    when(endpoint.environment()).thenReturn(environment);
    when(endpoint.context()).thenReturn(new CoreContext(environment, null, 1));
    when(environment.userAgent()).thenReturn("Couchbase Client Mock");

    queue = new ArrayDeque<QueryRequest>();
}
 
Example 13
Source Project: couchbase-jvm-core   Source File: SearchHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setup() {

    responseBuffer = new Disruptor<ResponseEvent>(new EventFactory<ResponseEvent>() {
        @Override
        public ResponseEvent newInstance() {
            return new ResponseEvent();
        }
    }, 1024, Executors.newCachedThreadPool());

    firedEvents = Collections.synchronizedList(new ArrayList<CouchbaseMessage>());
    latch = new CountDownLatch(1);
    responseBuffer.handleEventsWith(new EventHandler<ResponseEvent>() {
        @Override
        public void onEvent(ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
            firedEvents.add(event.getMessage());
            latch.countDown();
        }
    });
    responseRingBuffer = responseBuffer.start();

    CoreEnvironment environment = mock(CoreEnvironment.class);
    when(environment.scheduler()).thenReturn(Schedulers.computation());
    when(environment.maxRequestLifetime()).thenReturn(10000L); // 10 seconds
    when(environment.autoreleaseAfter()).thenReturn(2000L);
    when(environment.retryStrategy()).thenReturn(FailFastRetryStrategy.INSTANCE);
    endpoint = mock(AbstractEndpoint.class);
    when(endpoint.environment()).thenReturn(environment);
    when(environment.userAgent()).thenReturn("Couchbase Client Mock");

    queue = new ArrayDeque<SearchRequest>();
    handler = new SearchHandler(endpoint, responseRingBuffer, queue, false, false);
    channel = new EmbeddedChannel(handler);
}
 
Example 14
Source Project: jstorm   Source File: RingBuffer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Ring Buffer with the specified producer type (SINGLE or MULTI)
 * 
 * @param producerType producer type to use {@link ProducerType}.
 * @param factory used to create events within the ring buffer.
 * @param bufferSize number of elements to create within the ring buffer.
 * @param waitStrategy used to determine how to wait for new elements to become available.
 * @throws IllegalArgumentException if bufferSize is less than 1 or not a power of 2
 */
public static <E> RingBuffer<E> create(ProducerType producerType, EventFactory<E> factory, int bufferSize, WaitStrategy waitStrategy) {
    switch (producerType) {
    case SINGLE:
        return createSingleProducer(factory, bufferSize, waitStrategy);
    case MULTI:
        return createMultiProducer(factory, bufferSize, waitStrategy);
    default:
        throw new IllegalStateException(producerType.toString());
    }
}
 
Example 15
Source Project: sofa-jraft   Source File: DefaultRheaKVStore.java    License: Apache License 2.0 4 votes vote down vote up
public GetBatching(EventFactory<KeyEvent> factory, String name, EventHandler<KeyEvent> handler) {
    super(factory, batchingOpts.getBufSize(), name, handler);
}
 
Example 16
Source Project: sofa-jraft   Source File: DefaultRheaKVStore.java    License: Apache License 2.0 4 votes vote down vote up
public PutBatching(EventFactory<KVEvent> factory, String name, PutBatchingHandler handler) {
    super(factory, batchingOpts.getBufSize(), name, handler);
}
 
Example 17
Source Project: sofa-jraft   Source File: DisruptorBuilder.java    License: Apache License 2.0 4 votes vote down vote up
public EventFactory<T> getEventFactory() {
    return this.eventFactory;
}
 
Example 18
Source Project: sofa-jraft   Source File: DisruptorBuilder.java    License: Apache License 2.0 4 votes vote down vote up
public DisruptorBuilder<T> setEventFactory(final EventFactory<T> eventFactory) {
    this.eventFactory = eventFactory;
    return this;
}
 
Example 19
@Bean
@ConditionalOnMissingBean
public EventFactory<DisruptorEvent> eventFactory() {
	return new DisruptorBindEventFactory();
}
 
Example 20
@Bean
@ConditionalOnMissingBean
public EventFactory<DisruptorEvent> eventFactory() {
	return new DisruptorBindEventFactory();
}
 
Example 21
Source Project: camunda-bpm-reactor   Source File: HashWheelTimer.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Create a new {@code HashWheelTimer} using the given timer {@param resolution} and {@param wheelSize}. All times
 * will
 * rounded up to the closest multiple of this resolution.
 *
 * @param name      name for daemon thread factory to be displayed
 * @param res       resolution of this timer in milliseconds
 * @param wheelSize size of the Ring Buffer supporting the Timer, the larger the wheel, the less the lookup time is
 *                  for sparse timeouts. Sane default is 512.
 * @param strategy  strategy for waiting for the next tick
 * @param exec      Executor instance to submit tasks to
 */
public HashWheelTimer(String name, int res, int wheelSize, WaitStrategy strategy, Executor exec) {
  this.waitStrategy = strategy;

  this.wheel = RingBuffer.createSingleProducer(new EventFactory<Set<TimerPausable>>() {
    @Override
    public Set<TimerPausable> newInstance() {
      return new ConcurrentSkipListSet<TimerPausable>();
    }
  }, wheelSize);

  this.resolution = res;
  this.loop = new NamedDaemonThreadFactory(name).newThread(new Runnable() {
    @Override
    public void run() {
      long deadline = System.currentTimeMillis();

      while (true) {
        Set<TimerPausable> registrations = wheel.get(wheel.getCursor());

        for (TimerPausable r : registrations) {
          if (r.isCancelled()) {
            registrations.remove(r);
          } else if (r.ready()) {
            executor.execute(r);
            registrations.remove(r);

            if (!r.isCancelAfterUse()) {
              reschedule(r);
            }
          } else if (r.isPaused()) {
            reschedule(r);
          } else {
            r.decrement();
          }
        }

        deadline += resolution;

        try {
          waitStrategy.waitUntil(deadline);
        } catch (InterruptedException e) {
          return;
        }

        wheel.publish(wheel.next());
      }
    }
  });

  this.executor = exec;
  this.start();
}
 
Example 22
Source Project: disruptor-spring-manager   Source File: BaseDisruptorConfig.java    License: MIT License 4 votes vote down vote up
protected EventFactory<T> getEventFactory() {
	return eventFactory;
}
 
Example 23
Source Project: disruptor-spring-manager   Source File: BaseDisruptorConfig.java    License: MIT License 4 votes vote down vote up
public void setEventFactory(EventFactory<T> eventFactory) {
	this.eventFactory = eventFactory;
}
 
Example 24
Source Project: jstorm   Source File: RingBuffer.java    License: Apache License 2.0 4 votes vote down vote up
private void fill(EventFactory<E> eventFactory) {
    for (int i = 0; i < entries.length; i++) {
        entries[i] = eventFactory.newInstance();
    }
}
 
Example 25
Source Project: async-framework   Source File: DefaultDisruptorQueue.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 使用指定的事件工厂和线程池进行构建
 * @param eventFactory
 * @param executor
 * @param size
 */
public DefaultDisruptorQueue(final EventFactory<QueueEvent> eventFactory, final Executor executor, int size) {
	this.disruptor = new Disruptor<QueueEvent>(eventFactory, size, executor);
}
 
Example 26
Source Project: jstorm   Source File: RingBuffer.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Create a new multiple producer RingBuffer with the specified wait strategy.
 * 
 * @see MultiProducerSequencer
 * @param factory used to create the events within the ring buffer.
 * @param bufferSize number of elements to create within the ring buffer.
 * @param waitStrategy used to determine how to wait for new elements to become available.
 * @throws IllegalArgumentException if bufferSize is less than 1 or not a power of 2
 */
public static <E> RingBuffer<E> createMultiProducer(EventFactory<E> factory, int bufferSize, WaitStrategy waitStrategy) {
    MultiProducerSequencer sequencer = new MultiProducerSequencer(bufferSize, waitStrategy);

    return new RingBuffer<E>(factory, sequencer);
}
 
Example 27
Source Project: jstorm   Source File: RingBuffer.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Create a new multiple producer RingBuffer using the default wait strategy {@link BlockingWaitStrategy}.
 * 
 * @see MultiProducerSequencer
 * @param factory used to create the events within the ring buffer.
 * @param bufferSize number of elements to create within the ring buffer.
 * @throws IllegalArgumentException if <tt>bufferSize</tt> is less than 1 or not a power of 2
 */
public static <E> RingBuffer<E> createMultiProducer(EventFactory<E> factory, int bufferSize) {
    return createMultiProducer(factory, bufferSize, new BlockingWaitStrategy());
}
 
Example 28
Source Project: jstorm   Source File: RingBuffer.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Create a new single producer RingBuffer with the specified wait strategy.
 * 
 * @see SingleProducerSequencer
 * @param factory used to create the events within the ring buffer.
 * @param bufferSize number of elements to create within the ring buffer.
 * @param waitStrategy used to determine how to wait for new elements to become available.
 * @throws IllegalArgumentException if bufferSize is less than 1 or not a power of 2
 */
public static <E> RingBuffer<E> createSingleProducer(EventFactory<E> factory, int bufferSize, WaitStrategy waitStrategy) {
    SingleProducerSequencer sequencer = new SingleProducerSequencer(bufferSize, waitStrategy);

    return new RingBuffer<E>(factory, sequencer);
}
 
Example 29
Source Project: jstorm   Source File: RingBuffer.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Create a new single producer RingBuffer using the default wait strategy {@link BlockingWaitStrategy}.
 * 
 * @see MultiProducerSequencer
 * @param factory used to create the events within the ring buffer.
 * @param bufferSize number of elements to create within the ring buffer.
 * @throws IllegalArgumentException if <tt>bufferSize</tt> is less than 1 or not a power of 2
 */
public static <E> RingBuffer<E> createSingleProducer(EventFactory<E> factory, int bufferSize) {
    return createSingleProducer(factory, bufferSize, new BlockingWaitStrategy());
}