# ThreadProfiler Demo

## What Is It

The `ThreadProfiler` constantly records the stacktraces of all or some of your threads to help developers identify performance bottlenecks.

## How To Use It

You can configure a profiler by calling:

    ThreadProfiler profiler = new ThreadProfiler(Thread.currentThread());
    profiler.setActive(true);
    try {
      doSomethingInteresting();
    } finally {
      profiler.setActive(false);
      profiler.writeOutput(profilerFile);
    }

## How It Works

While it is active the profiler runs a helper daemon thread that constantly polls the stacktraces of designated threads.

You can adjust the interval between polling. (Personally I recommend 50 ms.)

The stacktraces are then merged together, including how often each stacktrace line is observed.

The output is a plain text String (that requires viewing in a monospaced font) that shows these composite stacktraces. It shows what percentage of the time was observed in each method, and how often the thread was observed in each possible state (RUNNABLE, BLOCKED, WAITING, etc.)

Using a pinch of reflection (just to inspect method properties -- not to invoke anything) this also tries to identify which methods are synchronized. The output clearly identifies methods that are definitely synchronized. (If the profiler is unable to determine if something is synchronized or not: it errs on the side of not reporting anything.)

The output also flags the most recent stack trace elements with a "=>" prefix.

## Discussion

I only recommend this as a last resort, simply because there are lots of great professionally developed tools out there that already do similar things.

At my work we have a license for Your Kit. In the last few years I've also used HPROF. I'm sure there are many other great options, too.

But I'm definitely keeping this in my toolbelt. A couple of times in the last decade I've been in a position where I could run Java code on a remote server, but I couldn't otherwise inspect it. This profiler worked great at identifying bottlenecks we needed to focus on. Or alternatively: if I'm testing something on a borrowed machine that I don't want to install developer tools on, then this is a great option to guarantee a minimal footprint.

See also the EventDispatchThreadMonitor.