Created
September 26, 2011 20:13
-
-
Save ajsutton/1243275 to your computer and use it in GitHub Desktop.
Disruptor Example of Background Logging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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