Debugging Trick in Eclipse

Today a friend asked me if you could execute an action in Eclipse on a breakpoint. I thought for sure that that would work, but decided I had to check before I said yes. Well… there is no such feature in Eclipse, but here is a cool work-around.

Problem

The problem that my friend had was that he’d like to inject some code when the breakpoint triggered, print out some stuff, then resume operation as quickly as possible. The reasons for this may be many, but the most typical is that you’re running in some real-time (or semi-real-time) scenario where stopping in the debugger may make you miss a deadline.

Solution

Create a specialized break in Eclipse that has the following traits:

  • Make the breakpoint conditional
  • Specify that that you only want to suspend the thread when the condition is true.
  • Create a condition with side-effect

Example

In this example we’ll show some simple code that simply iterate through all numbers from 0 through 99 and summarize them all. At the line where we accumulate the sequence, we’d like to print out the number and as quickly as possible continue the execution of the program.

Here is some the sample code:

The example is rather silly, but it will do for this purpose.

Steps to make the print work…

  1. Create a breakpoint on line 16 ( “j += i;”)
  2. Go to the debug view in Eclipse
  3. Right-click on the breakpoint and select properties
    image
    image[9]
  4. Enter the code to print out ‘i’ and return false (as shown below):
    image[10]
  5. Run the program in debug mode

Notice that the application now print out the i on all iterations!

Anecdote

I was quite exciting when I saw this. If you are familiar with Aspect Oriented Programming, this is quick way to patch in an aspect! Here is another silly example.

image[14]-1

We are now patching the value of ‘j’…. I just can’t wait until someone leaves their computer on while they debug a problem…. Can you imagine the look on their face as I make some random assignments 🙂

Summary

In this article I shown an advanced debugging technique not commonly known in Eclipse. The technique can be used to quickly print or patch values without slowing down a program significantly (or have a lot of fun with your colleagues).

No Comments Yet.

Leave a comment