Introduction
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:
1: package com.scispike.demo;
2:
3: /**
4: * Dummy class created to
5: * demonstrate some debug tricks
6: *
7: * @author pgraff
8: *
9: */
10: public class DebugDemo {
11:
12: public static void main(String[] args) {
13: int j = 0;
14: for (int i = 0; i < 100; i++)
15: {
16: j += i;
17: }
18: System.out.println(j);
19:
20: }
21:
22: }
The example is rather silly, but it will do for this purpose.
Steps to make the print work…
- Create a breakpoint on line 16 ( “j += i;”)
- Go to the debug view in Eclipse
- Right-click on the breakpoint and select properties
- Enter the code to print out ‘i’ and return false (as shown below):
- 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.
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).
View comments