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

The following examples show how to use com.lmax.disruptor.dsl.Disruptor. 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: 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 2
/**
 * 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 3
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 4
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 5
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 6
Source Project: james   Source File: DisruptorAsyncScriptEngine.java    License: Apache License 2.0 6 votes vote down vote up
DisruptorAsyncScriptEngine(ScriptEngine delegate, int numberOfWorkers, int jobQueueSize) {


        // Specify the size of the ring buffer, must be power of 2.
        bufferSize = nextPowerOf2(jobQueueSize);

        // Construct the Disruptor
        this.executor = MoreExecutors.createNamedDaemonExecutorService(
                "async-script-engine-thread-pool-%d", numberOfWorkers);
        disruptor =
                new Disruptor<>(new JobEvent.Factory(), bufferSize, executor);
        // Start the Disruptor, starts all threads running
        disruptor.handleEventsWith(new JobEventHandler());
        disruptor.start();

        this.delegate = Objects.requireNonNull(delegate);
        LOG.trace(() -> "Script engine worker pool created with " + numberOfWorkers + " threads");
    }
 
Example 7
Source Project: james   Source File: DisruptorAsyncPublisher.java    License: Apache License 2.0 6 votes vote down vote up
DisruptorAsyncPublisher(
    EventPublisher delegate,
    String threadPoolNameFormat,
    int numberOfWorkers,
    int maxQueueCapacity) {

    // Specify the size of the ring buffer, must be power of 2.
    bufferSize = nextPowerOf2(maxQueueCapacity);


    // Construct the Disruptor
    executor = MoreExecutors.createNamedDaemonExecutorService(threadPoolNameFormat, numberOfWorkers);
    disruptor = new Disruptor<>(new JobEvent.Factory(), bufferSize, executor);
    // Start the Disruptor, starts all threads running
    disruptor.handleEventsWith(new JobEventHandler());
    disruptor.start();

    // Get the ring buffer from the Disruptor to be used for publishing.
    this.delegate = Objects.requireNonNull(delegate);
    LOG.trace(() -> "Async worker pool for " + delegate.getId() + " created with " + numberOfWorkers + (numberOfWorkers > 1 ? " threads" : " thread"));
}
 
Example 8
@Bean
public JmsMessageSender responseMessageSender(@Value("${jms-sender.ring-buffer-size}")int ringBufferSize) throws JMSException {

  DisruptorJmsMessageSender disruptorJmsMessageSender = DisruptorJmsMessageSenderFactory.create(
      responseSession(),
      responseMessageProducer(),
      new ArtemisMessageDtoDupMessageDetectStrategy(),
      ringBufferSize
  );

  Disruptor disruptor = disruptorJmsMessageSender.getDisruptor();

  BeanRegisterUtils.registerSingleton(
      applicationContext,
      "responseMessageSenderLifeCycleContainer",
      new DisruptorLifeCycleContainer("responseMessageSender", disruptor, Ordered.LOWEST_PRECEDENCE)
  );

  return disruptorJmsMessageSender;

}
 
Example 9
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 10
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 11
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 12
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 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
Source Project: logging-log4j2   Source File: AsyncLogger.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Enqueues the specified log event data for logging in a background thread.
 * <p>
 * This creates a new varargs Object array for each invocation, but does not store any non-JDK classes in a
 * {@code ThreadLocal} to avoid memory leaks in web applications (see LOG4J2-1172).
 *
 * @param fqcn fully qualified name of the caller
 * @param location location of the caller.
 * @param level level at which the caller wants to log the message
 * @param marker message marker
 * @param message the log message
 * @param thrown a {@code Throwable} or {@code null}
 */
private void logWithVarargTranslator(final String fqcn, final StackTraceElement location, final Level level,
                                     final Marker marker, final Message message, final Throwable thrown) {
    // Implementation note: candidate for optimization: exceeds 35 bytecodes.

    final Disruptor<RingBufferLogEvent> disruptor = loggerDisruptor.getDisruptor();
    if (disruptor == null) {
        LOGGER.error("Ignoring log event after Log4j has been shut down.");
        return;
    }
    // if the Message instance is reused, there is no point in freezing its message here
    if (!isReused(message)) {
        InternalAsyncUtil.makeMessageImmutable(message);
    }
    // calls the translateTo method on this AsyncLogger
    if (!disruptor.getRingBuffer().tryPublishEvent(this,
        this, // asyncLogger: 0
        location, // location: 1
        fqcn, // 2
        level, // 3
        marker, // 4
        message, // 5
        thrown)) { // 6
        handleRingBufferFull(location, fqcn, level, marker, message, thrown);
    }
}
 
Example 15
Source Project: elastic-rabbitmq   Source File: LongEventMain.java    License: 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 16
Source Project: Electrons   Source File: ListenerChainBuilderNew.java    License: MIT License 6 votes vote down vote up
private static void dealWithDisruptorFromTail(ListenerChain chain, Disruptor<ElectronsHolder> disruptor) {
    if (idOnly(chain.getId(), chain.getAfter())) {
        return;
    }
    List<ListenerChain> befores = chain.getBefores();
    if (CollectionUtils.isEmpty(befores)) {
        return;
    }
    for (ListenerChain c : befores) {
        dealWithDisruptorFromTail(c, disruptor);
    }
    ProxyHandler[] handlers = new ProxyHandler[befores.size()];
    for (int i = 0; i < befores.size(); i++) {
        handlers[i] = befores.get(i).getProxyHandler();
    }
    disruptor.after(handlers).handleEventsWith(chain.getProxyHandler());
}
 
Example 17
Source Project: cicada   Source File: DisruptorTransfer.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public DisruptorTransfer(final SpanEventHandler spanEventHandler, final int buffSize) {
  // Executor executor = Executors.newCachedThreadPool();
  final ThreadFactory threadFactory = Executors.defaultThreadFactory();

  // The factory for the event
  final SpanEventFactory factory = new SpanEventFactory();

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

  // Construct the Disruptor
  disruptor = new Disruptor<SpanEvent>(factory, bufferSize, threadFactory);

  // Connect the handler
  // disruptor.handleEventsWith(new
  // SpanEventHandler("http://localhost:9080/upload"));
  disruptor.handleEventsWith(spanEventHandler);

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

  final RingBuffer<SpanEvent> ringBuffer = disruptor.getRingBuffer();
  producer = new SpanEventProducer(ringBuffer);
}
 
Example 18
@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 19
@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 20
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 21
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 22
Source Project: logging-log4j2   Source File: AsyncLoggerDisruptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Returns {@code true} if the specified disruptor is null.
     */
private boolean hasLog4jBeenShutDown(final Disruptor<RingBufferLogEvent> aDisruptor) {
    if (aDisruptor == null) { // LOG4J2-639
        LOGGER.warn("Ignoring log event after log4j was shut down");
        return true;
    }
    return false;
}
 
Example 23
Source Project: youkefu   Source File: UKTools.java    License: Apache License 2.0 5 votes vote down vote up
public static void published(UserEvent event){
	@SuppressWarnings("unchecked")
	Disruptor<UserDataEvent> disruptor = (Disruptor<UserDataEvent>) UKDataContext.getContext().getBean("disruptor") ;
	long seq = disruptor.getRingBuffer().next();
	disruptor.getRingBuffer().get(seq).setEvent(event); ;
	disruptor.getRingBuffer().publish(seq);
}
 
Example 24
Source Project: elasticactors   Source File: ThreadBoundExecutorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void shutdown() {
    logger.info("Shutting down the (Disruptor)ThreadBoundExecutor[{}]",threadFactory);
    if (shuttingDown.compareAndSet(false, true)) {
        for (Disruptor<ThreadBoundEventWrapper> disruptor : disruptors) {
            // @todo: we may want to have a timeout here
            disruptor.shutdown();
        }
    }
    logger.info("(Disruptor)ThreadBoundExecutor[{}] shut down completed",threadFactory);
}
 
Example 25
Source Project: youkefu   Source File: UKTools.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked"})
public static void ai(UserEvent event){
	Disruptor<AiEvent> disruptor = (Disruptor<AiEvent>) UKDataContext.getContext().getBean("ai") ;
	long seq = disruptor.getRingBuffer().next();
	disruptor.getRingBuffer().get(seq).setEvent(event); ;
	disruptor.getRingBuffer().publish(seq);
}
 
Example 26
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 27
Source Project: logging-log4j2   Source File: AsyncLogger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Enqueues the specified log event data for logging in a background thread.
 * <p>
 * This creates a new varargs Object array for each invocation, but does not store any non-JDK classes in a
 * {@code ThreadLocal} to avoid memory leaks in web applications (see LOG4J2-1172).
 *
 * @param fqcn fully qualified name of the caller
 * @param level level at which the caller wants to log the message
 * @param marker message marker
 * @param message the log message
 * @param thrown a {@code Throwable} or {@code null}
 */
private void logWithVarargTranslator(final String fqcn, final Level level, final Marker marker,
        final Message message, final Throwable thrown) {
    // Implementation note: candidate for optimization: exceeds 35 bytecodes.

    final Disruptor<RingBufferLogEvent> disruptor = loggerDisruptor.getDisruptor();
    if (disruptor == null) {
        LOGGER.error("Ignoring log event after Log4j has been shut down.");
        return;
    }
    // if the Message instance is reused, there is no point in freezing its message here
    if (!isReused(message)) {
        InternalAsyncUtil.makeMessageImmutable(message);
    }
    StackTraceElement location = null;
    // calls the translateTo method on this AsyncLogger
    if (!disruptor.getRingBuffer().tryPublishEvent(this,
            this, // asyncLogger: 0
            (location = calcLocationIfRequested(fqcn)), // location: 1
            fqcn, // 2
            level, // 3
            marker, // 4
            message, // 5
            thrown)) { // 6
        handleRingBufferFull(location, fqcn, level, marker, message, thrown);
    }
}
 
Example 28
Source Project: logging-log4j2   Source File: AsyncLoggerConfigDisruptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns {@code true} if the specified disruptor is null.
 */
private boolean hasLog4jBeenShutDown(final Disruptor<Log4jEventWrapper> aDisruptor) {
    if (aDisruptor == null) { // LOG4J2-639
        LOGGER.warn("Ignoring log event after log4j was shut down");
        return true;
    }
    return false;
}
 
Example 29
Source Project: logging-log4j2   Source File: AsyncLoggerConfigDisruptor.java    License: Apache License 2.0 5 votes vote down vote up
private int remainingDisruptorCapacity() {
    final Disruptor<Log4jEventWrapper> temp = disruptor;
    if (hasLog4jBeenShutDown(temp)) {
        return -1;
    }
    return (int) temp.getRingBuffer().remainingCapacity();
}
 
Example 30
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);
    }
}