Skip to content

Instantly share code, notes, and snippets.

@ajsutton
Created September 26, 2011 20:13
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ajsutton/1243275 to your computer and use it in GitHub Desktop.
Save ajsutton/1243275 to your computer and use it in GitHub Desktop.
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