Java: How can I see what parts of my code are running the most? (profiling)

By : jjnguy

I am writing a simple checkers game in Java. When I mouse over the board my processor ramps up to 50% (100% on a core).

I would like to find out what part of my code(assuming its my fault) is executing during this.

I have tried debugging, but step-through debugging doesn't work very well in this case.

Is there any tool that can tell me where my problem lies? I am currently using Eclipse.

By : jjnguy


This is a typically 'High CPU' problem.

There are two kind of high CPU problems

a) Where on thread is using 100% CPU of one core (This is your scenario)

b) CPU usage is 'abnormally high' when we execute certain actions. In such cases CPU may not be 100% but will be abnormally high. Typically this happens when we have CPU intensive operations in the code like XML parsing, serialization de-serialization etc.

Case (a) is easy to analyze. When you experience 100% CPU 5-6 thread dumps in 30 sec interval. Look for a thread which is active (in "runnable" state) and which is inside the same method (you can infer that by monitoring the thread stack). Most probably that you will see a 'busy wait' (see code below for an example)

  if(status) break;
  // Thread.sleep(60000); // such a statement would have avoided busy wait

Case (b) also can be analyzed using thread dumps taken in equal interval. If you are lucky you will be able to find out the problem code, If you are not able to identify the problem code by using thread dump. You need to resort to profilers. In my experience YourKit profiler is very good.

I always try with thread dumps first. Profilers will only be last resort. In 80% of the cases we will be able to identify using thread dumps.

In single-threaded code, I find adding some statements like this: System.out.println("A: "+ System.currentTimeMillis()); is simpler and as effective as using a profiler. You can soon narrow down the part of the code causing the problem.

If you're using Sun Java 6, then the most recent JDK releases come with JVisualVM in the bin directory. This is a capable monitoring and profiling tool that will require very little effort to use - you don't even need to start your program with special parameters - JVisualVM simply lists all the currently running java processes and you choose the one you want to play with.

This tool will tell you which methods are using all the processor time.

There are plenty of more powerful tools out there, but have a play with a free one first. Then, when you read about what other features are available out there, you'll have an inking about how they might help you.

This video can help you solving your question :)
By: admin