Search in sources :

Example 11 with AbstractRunnable

use of org.spf4j.base.AbstractRunnable in project spf4j by zolyfarkas.

the class Monitor method main.

@SuppressWarnings("checkstyle:regexp")
public static void main(final String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    int sepPos = args.length;
    for (int i = 0; i < args.length; i++) {
        if ("--".equals(args[i])) {
            sepPos = i;
            break;
        }
    }
    String[] newArgs;
    String[] ownArgs;
    if (sepPos == args.length) {
        newArgs = new String[0];
        ownArgs = args;
    } else {
        newArgs = new String[args.length - sepPos - 1];
        ownArgs = new String[sepPos];
        System.arraycopy(args, sepPos + 1, newArgs, 0, newArgs.length);
        System.arraycopy(args, 0, ownArgs, 0, sepPos);
    }
    Options options = new Options();
    CmdLineParser parser = new CmdLineParser(options);
    try {
        parser.parseArgument(ownArgs);
    } catch (CmdLineException e) {
        System.err.println("Error: " + e.getMessage() + "\nUsage:");
        parser.printUsage(System.err);
        System.exit(SysExits.EX_USAGE.exitCode());
    }
    final Sampler sampler = new Sampler(options.sampleInterval, options.dumpInterval, (t) -> new FastStackCollector(false, true, new Thread[] { t }), options.dumpFolder, options.dumpFilePrefix);
    Runtime.getRuntime().addShutdownHook(new Thread(new AbstractRunnable() {

        @Override
        public void doRun() throws InterruptedException, IOException {
            sampler.stop();
            sampler.dumpToFile();
            sampler.dispose();
        }
    }, "Sampling report"));
    sampler.registerJmx();
    if (options.startSampler) {
        sampler.start();
    }
    Class.forName(options.mainClass).getMethod("main", String[].class).invoke(null, (Object) newArgs);
    System.exit(SysExits.OK.exitCode());
}
Also used : AbstractRunnable(org.spf4j.base.AbstractRunnable) CmdLineParser(org.kohsuke.args4j.CmdLineParser) CmdLineException(org.kohsuke.args4j.CmdLineException)

Example 12 with AbstractRunnable

use of org.spf4j.base.AbstractRunnable in project spf4j by zolyfarkas.

the class Sampler method start.

@JmxExport(description = "start stack sampling")
public synchronized void start() {
    if (stopped) {
        stopped = false;
        final int stNanos = sampleTimeNanos;
        samplerFuture = DefaultExecutor.INSTANCE.submit(new AbstractRunnable("SPF4J-Sampling-Thread") {

            @SuppressWarnings("SleepWhileInLoop")
            @SuppressFBWarnings({ "MDM_THREAD_YIELD", "PREDICTABLE_RANDOM" })
            @Override
            public void doRun() throws IOException, InterruptedException {
                synchronized (sync) {
                    stackCollector = stackCollectorSupp.get(Thread.currentThread());
                }
                final ThreadLocalRandom random = ThreadLocalRandom.current();
                int dumpCounterNanos = 0;
                int coarseCounter = 0;
                int coarseCount = STOP_FLAG_READ_MILLIS / stNanos;
                boolean lstopped = stopped;
                int sleepTimeNanos = 0;
                int halfStNanos = stNanos / 2;
                if (halfStNanos == 0) {
                    halfStNanos = 1;
                }
                int maxSleeepNanos = stNanos + halfStNanos;
                while (!lstopped) {
                    synchronized (sync) {
                        stackCollector.sample();
                    }
                    dumpCounterNanos += sleepTimeNanos;
                    coarseCounter++;
                    if (coarseCounter >= coarseCount) {
                        coarseCounter = 0;
                        lstopped = stopped;
                    }
                    if (dumpCounterNanos >= dumpTimeNanos) {
                        long nanosSinceLastDump = TimeSource.nanoTime() - lastDumpTimeNanos;
                        if (nanosSinceLastDump >= dumpTimeNanos) {
                            dumpCounterNanos = 0;
                            dumpToFile();
                        } else {
                            dumpCounterNanos -= dumpTimeNanos - nanosSinceLastDump;
                        }
                    }
                    sleepTimeNanos = random.nextInt(halfStNanos, maxSleeepNanos);
                    TimeUnit.NANOSECONDS.sleep(sleepTimeNanos);
                }
            }
        });
    } else {
        throw new IllegalStateException("Sampling can only be started once for " + this);
    }
}
Also used : AbstractRunnable(org.spf4j.base.AbstractRunnable) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) JmxExport(org.spf4j.jmx.JmxExport)

Example 13 with AbstractRunnable

use of org.spf4j.base.AbstractRunnable in project spf4j by zolyfarkas.

the class ThreadUsageSampler method start.

@JmxExport
public static synchronized void start(@JmxExport("sampleTimeMillis") final int sampleTime, @JmxExport("withStackTraces") final boolean withStackTraces) {
    if (samplingFuture == null) {
        final MeasurementRecorder cpuUsage = RecorderFactory.createDirectRecorder("peak-thread-count", "count", sampleTime);
        samplingFuture = DefaultScheduler.INSTANCE.scheduleWithFixedDelay(new AbstractRunnable() {

            private int maxThreadsNr = 0;

            @Override
            public void doRun() {
                final int peakThreadCount = TH_BEAN.getPeakThreadCount();
                cpuUsage.record(peakThreadCount);
                if (peakThreadCount > maxThreadsNr) {
                    Thread[] ths = Threads.getThreads();
                    if (ths.length > PEAK_THREAD_NAMES.size()) {
                        if (withStackTraces) {
                            StackTraceElement[][] stackTraces = Threads.getStackTraces(ths);
                            PEAK_THREAD_TRACES.clear();
                            PEAK_THREAD_TRACES.addAll(Arrays.asList(stackTraces));
                        }
                        PEAK_THREAD_NAMES.clear();
                        int i = 0;
                        for (Thread th : ths) {
                            PEAK_THREAD_NAMES.add(th.getName());
                            if (th.isDaemon()) {
                                PEAK_THREAD_DAEMON.set(i);
                            } else {
                                PEAK_THREAD_DAEMON.clear(i);
                            }
                            i++;
                        }
                    }
                    maxThreadsNr = peakThreadCount;
                }
                TH_BEAN.resetPeakThreadCount();
            }
        }, sampleTime, sampleTime, TimeUnit.MILLISECONDS);
    } else {
        throw new IllegalStateException("Thread sampling already started " + samplingFuture);
    }
}
Also used : AbstractRunnable(org.spf4j.base.AbstractRunnable) MeasurementRecorder(org.spf4j.perf.MeasurementRecorder) JmxExport(org.spf4j.jmx.JmxExport)

Example 14 with AbstractRunnable

use of org.spf4j.base.AbstractRunnable in project spf4j by zolyfarkas.

the class PipedOutputStreamTest method test.

public static void test(final String testStr, final int buffSize, final boolean buffered) throws IOException {
    final PipedOutputStream pos = new PipedOutputStream(buffSize);
    final InputStream pis;
    if (buffered) {
        pis = new MemorizingBufferedInputStream(pos.getInputStream());
    } else {
        pis = pos.getInputStream();
    }
    DefaultExecutor.INSTANCE.execute(new AbstractRunnable() {

        @Override
        public void doRun() throws Exception {
            try (OutputStream os = pos) {
                final byte[] utf8 = Strings.toUtf8(testStr);
                os.write(utf8[0]);
                os.write(utf8, 1, 10);
                os.write(utf8, 11, utf8.length - 11);
            }
        }
    });
    StringBuilder sb = new StringBuilder();
    try (InputStream is = pis) {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = is.read(buffer)) > 0) {
            sb.append(Strings.fromUtf8(buffer, 0, read));
        }
    }
    Assert.assertEquals(testStr, sb.toString());
}
Also used : AbstractRunnable(org.spf4j.base.AbstractRunnable) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 15 with AbstractRunnable

use of org.spf4j.base.AbstractRunnable in project spf4j by zolyfarkas.

the class PipedStreamsBenchmark method testSpf.

private void testSpf(final String testStr, final int buffSize) throws IOException {
    final PipedOutputStream pos = new PipedOutputStream(buffSize);
    final InputStream pis = pos.getInputStream();
    DefaultExecutor.INSTANCE.execute(new AbstractRunnable() {

        @Override
        public void doRun() throws Exception {
            try (OutputStream os = pos) {
                final byte[] utf8 = Strings.toUtf8(testStr);
                os.write(utf8[0]);
                os.write(utf8, 1, 10);
                os.write(utf8, 11, 10);
                os.write(utf8, 21, utf8.length - 21);
            }
        }
    });
    StringBuilder sb = new StringBuilder();
    try (InputStream is = pis) {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = is.read(buffer)) > 0) {
            sb.append(Strings.fromUtf8(buffer, 0, read));
        }
    }
    Assert.assertEquals(testStr, sb.toString());
}
Also used : AbstractRunnable(org.spf4j.base.AbstractRunnable) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Aggregations

AbstractRunnable (org.spf4j.base.AbstractRunnable)16 IOException (java.io.IOException)6 JmxExport (org.spf4j.jmx.JmxExport)4 InputStream (java.io.InputStream)3 OutputStream (java.io.OutputStream)3 MeasurementRecorder (org.spf4j.perf.MeasurementRecorder)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 Test (org.junit.Test)2 TObjectLongMap (gnu.trove.map.TObjectLongMap)1 TObjectLongHashMap (gnu.trove.map.hash.TObjectLongHashMap)1 File (java.io.File)1 UncheckedIOException (java.io.UncheckedIOException)1 InetSocketAddress (java.net.InetSocketAddress)1 ByteBuffer (java.nio.ByteBuffer)1 ClosedByInterruptException (java.nio.channels.ClosedByInterruptException)1 DatagramChannel (java.nio.channels.DatagramChannel)1 ArrayList (java.util.ArrayList)1 ForkJoinPool (java.util.concurrent.ForkJoinPool)1 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)1 BeforeClass (org.junit.BeforeClass)1