001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.core.async; 018 019import com.lmax.disruptor.LifecycleAware; 020import com.lmax.disruptor.Sequence; 021import com.lmax.disruptor.SequenceReportingEventHandler; 022 023/** 024 * This event handler gets passed messages from the RingBuffer as they become 025 * available. Processing of these messages is done in a separate thread, 026 * controlled by the {@code Executor} passed to the {@code Disruptor} 027 * constructor. 028 */ 029public class RingBufferLogEventHandler implements 030 SequenceReportingEventHandler<RingBufferLogEvent>, LifecycleAware { 031 032 private static final int NOTIFY_PROGRESS_THRESHOLD = 50; 033 private Sequence sequenceCallback; 034 private int counter; 035 private long threadId = -1; 036 037 @Override 038 public void setSequenceCallback(final Sequence sequenceCallback) { 039 this.sequenceCallback = sequenceCallback; 040 } 041 042 @Override 043 public void onEvent(final RingBufferLogEvent event, final long sequence, 044 final boolean endOfBatch) throws Exception { 045 event.execute(endOfBatch); 046 event.clear(); 047 // notify the BatchEventProcessor that the sequence has progressed. 048 // Without this callback the sequence would not be progressed 049 // until the batch has completely finished. 050 notifyCallback(sequence); 051 } 052 053 private void notifyCallback(long sequence) { 054 if (++counter > NOTIFY_PROGRESS_THRESHOLD) { 055 sequenceCallback.set(sequence); 056 counter = 0; 057 } 058 } 059 060 /** 061 * Returns the thread ID of the background consumer thread, or {@code -1} if the background thread has not started 062 * yet. 063 * @return the thread ID of the background consumer thread, or {@code -1} 064 */ 065 public long getThreadId() { 066 return threadId; 067 } 068 069 @Override 070 public void onStart() { 071 threadId = Thread.currentThread().getId(); 072 } 073 074 @Override 075 public void onShutdown() { 076 } 077}