下面列出了org.apache.logging.log4j.core.util.Constants#ENABLE_THREADLOCALS 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static int calculateRingBufferSize(final String propertyName) {
int ringBufferSize = Constants.ENABLE_THREADLOCALS ? RINGBUFFER_NO_GC_DEFAULT_SIZE : RINGBUFFER_DEFAULT_SIZE;
final String userPreferredRBSize = PropertiesUtil.getProperties().getStringProperty(propertyName,
String.valueOf(ringBufferSize));
try {
int size = Integer.parseInt(userPreferredRBSize);
if (size < RINGBUFFER_MIN_SIZE) {
size = RINGBUFFER_MIN_SIZE;
LOGGER.warn("Invalid RingBufferSize {}, using minimum size {}.", userPreferredRBSize,
RINGBUFFER_MIN_SIZE);
}
ringBufferSize = size;
} catch (final Exception ex) {
LOGGER.warn("Invalid RingBufferSize {}, using default size {}.", userPreferredRBSize, ringBufferSize);
}
return Integers.ceilingNextPowerOfTwo(ringBufferSize);
}
private MutableInstant getMutableInstant() {
if (Constants.ENABLE_THREADLOCALS) {
MutableInstant result = threadLocalMutableInstant.get();
if (result == null) {
result = new MutableInstant();
threadLocalMutableInstant.set(result);
}
return result;
}
return new MutableInstant();
}
public void format(final Instant instant, final StringBuilder output) {
if (Constants.ENABLE_THREADLOCALS) {
formatWithoutAllocation(instant, output);
} else {
formatWithoutThreadLocals(instant, output);
}
}
public static RecyclerFactory ofSpec(final String recyclerFactorySpec) {
// Determine the default capacity.
int defaultCapacity = Math.max(
2 * Runtime.getRuntime().availableProcessors() + 1,
8);
// TLA-, MPMC-, or ABQ-based queueing factory -- if nothing is specified.
if (recyclerFactorySpec == null) {
if (Constants.ENABLE_THREADLOCALS) {
return ThreadLocalRecyclerFactory.getInstance();
} else {
final Supplier<Queue<Object>> queueSupplier =
JCTOOLS_QUEUE_CLASS_AVAILABLE
? () -> new MpmcArrayQueue<>(defaultCapacity)
: () -> new ArrayBlockingQueue<>(defaultCapacity);
return new QueueingRecyclerFactory(queueSupplier);
}
}
// Is a dummy factory requested?
else if (recyclerFactorySpec.equals("dummy")) {
return DummyRecyclerFactory.getInstance();
}
// Is a TLA factory requested?
else if (recyclerFactorySpec.equals("threadLocal")) {
return ThreadLocalRecyclerFactory.getInstance();
}
// Is a queueing factory requested?
else if (recyclerFactorySpec.startsWith("queue")) {
return readQueueingRecyclerFactory(recyclerFactorySpec, defaultCapacity);
}
// Bogus input, bail out.
else {
throw new IllegalArgumentException(
"invalid recycler factory: " + recyclerFactorySpec);
}
}
public static void main(final String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Please specify thread count, target throughput (msg/sec) " +
"and logger library (Log4j1, Log4j2, Logback, JUL)");
return;
}
final int threadCount = Integer.parseInt(args[0]);
final double loadMessagesPerSec = Double.parseDouble(args[1]);
final String loggerLib = args.length > 2 ? args[2] : "Log4j2";
// print to console if ringbuffer is full
System.setProperty("log4j2.AsyncQueueFullPolicy", PrintingAsyncQueueFullPolicy.class.getName());
System.setProperty("AsyncLogger.RingBufferSize", String.valueOf(256 * 1024));
//System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
//System.setProperty("log4j.configurationFile", "perf3PlainNoLoc.xml");
if (System.getProperty("AsyncLogger.WaitStrategy") == null) {
System.setProperty("AsyncLogger.WaitStrategy", "Yield");
}
//for (Object key : System.getProperties().keySet()) {
// System.out.println(key + "=" + System.getProperty((String) key));
//}
// initialize the logger
final String wrapper = loggerLib.startsWith("Run") ? loggerLib : "Run" + loggerLib;
final String loggerWrapperClass = "org.apache.logging.log4j.core.async.perftest." + wrapper;
final IPerfTestRunner logger = Loader.newCheckedInstanceOf(loggerWrapperClass, IPerfTestRunner.class);
logger.log("Starting..."); // ensure initialized
Thread.sleep(100);
final int requiredProcessors = threadCount + 1 + 1; // producers + 1 consumer + 1 for OS
final IdleStrategy idleStrategy = Runtime.getRuntime().availableProcessors() > requiredProcessors
? new NoOpIdleStrategy()
: new YieldIdleStrategy();
System.out.printf("%s: %d threads, load is %,f msg/sec, using %s%n", loggerLib, threadCount,
loadMessagesPerSec, idleStrategy.getClass().getSimpleName());
// Warmup: run as many iterations of 50,000 calls to logger.log as we can in 1 minute
final long WARMUP_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(1);
final List<Histogram> warmupServiceTmHistograms = new ArrayList<>(threadCount);
final List<Histogram> warmupResponseTmHistograms = new ArrayList<>(threadCount);
final int WARMUP_COUNT = 50000 / threadCount;
runLatencyTest(logger, WARMUP_DURATION_MILLIS, WARMUP_COUNT, loadMessagesPerSec, idleStrategy,
warmupServiceTmHistograms, warmupResponseTmHistograms, threadCount);
System.out.println("-----------------Warmup done. load=" + loadMessagesPerSec);
if (!Constants.ENABLE_DIRECT_ENCODERS || !Constants.ENABLE_THREADLOCALS) {
//System.gc();
//Thread.sleep(5000);
}
System.out.println("-----------------Starting measured run. load=" + loadMessagesPerSec);
final long start = System.currentTimeMillis();
final List<Histogram> serviceTmHistograms = new ArrayList<>(threadCount);
final List<Histogram> responseTmHistograms = new ArrayList<>(threadCount);
PrintingAsyncQueueFullPolicy.ringbufferFull.set(0);
// Actual test: run as many iterations of 1,000,000 calls to logger.log as we can in 4 minutes.
final long TEST_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(4);
final int COUNT = (1000 * 1000) / threadCount;
runLatencyTest(logger, TEST_DURATION_MILLIS, COUNT, loadMessagesPerSec, idleStrategy, serviceTmHistograms,
responseTmHistograms, threadCount);
logger.shutdown();
final long end = System.currentTimeMillis();
// ... and report the results
final Histogram resultServiceTm = createResultHistogram(serviceTmHistograms, start, end);
resultServiceTm.outputPercentileDistribution(System.out, 1000.0);
writeToFile("s", resultServiceTm, (int) (loadMessagesPerSec / 1000), 1000.0);
final Histogram resultResponseTm = createResultHistogram(responseTmHistograms, start, end);
resultResponseTm.outputPercentileDistribution(System.out, 1000.0);
writeToFile("r", resultResponseTm, (int) (loadMessagesPerSec / 1000), 1000.0);
System.out.printf("%n%s: %d threads, load %,f msg/sec, ringbuffer full=%d%n", loggerLib, threadCount,
loadMessagesPerSec, PrintingAsyncQueueFullPolicy.ringbufferFull.get());
System.out.println("Test duration: " + (end - start) / 1000.0 + " seconds");
}