Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Disruptor Example of Background Logging
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BackgroundLogger
{
private static final int ENTRIES = 64;
private final ExecutorService executorService;
private final Disruptor<LogEntry> disruptor;
private final RingBuffer<LogEntry> ringBuffer;
BackgroundLogger()
{
executorService = Executors.newCachedThreadPool();
disruptor = new Disruptor<LogEntry>(LogEntry.FACTORY, ENTRIES, executorService);
disruptor.handleEventsWith(new LogEntryHandler());
disruptor.start();
ringBuffer = disruptor.getRingBuffer();
}
public void log(String text)
{
final long sequence = ringBuffer.next();
final LogEntry logEntry = ringBuffer.get(sequence);
logEntry.time = System.currentTimeMillis();
logEntry.level = level;
logEntry.text = text;
ringBuffer.publish(sequence);
}
public void stop()
{
disruptor.shutdown();
executorService.shutdownNow();
}
}
import com.lmax.disruptor.EventFactory;
class LogEntry
{
public static final EventFactory<LogEntry> FACTORY = new EventFactory<LogEntry>()
{
public LogEntry newInstance()
{
return new LogEntry();
}
};
long time;
int level;
String text;
}
import com.lmax.disruptor.EventHandler;
public class LogEntryHandler implements EventHandler<LogEntry>
{
public LogEntryHandler()
{
}
public void onEvent(final LogEntry logEntry, final long sequence, final boolean endOfBatch) throws Exception
{
// Write
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment