Peeking Inside The Box: attribute-oriented programming with java 1.5
In the previous article in this series, "Peeking Inside the Box, Part 1," I introduced the concepts of Attribute-Oriented Programming, Java 1.5 annotations, and bytecode instrumentation. I used these concepts to provide a JStatusBar GUI component that reports on the progress of an application without any explicit code. In this article I will introduce a completely different implementation of the same JStatusBar that uses thread sampling rather than bytecode instrumentation. I will then combine the two practices to develop a solution that has the best features of each .
In The Previous Article, I Also Defined A New Annotation, @Status, Which I Used Throughout My Code To Associate Methods with User-Readable Status Messages. For Example:
@Status ("Connecting to Database")
Public void connectiontoc (String URL) {
...
}
Exception Handling
As discussed in the previous article, I may want to write additional code which uses the @Status annotations for a different purpose. Let's consider the additional requirement that our application must catch all unhandled exceptions and display them to the user. Rather than providing a Java Stack TRACE, HOWEVER, IT SHOULD Only Display Methods That Have A @Status Annotation, And It Should Not Show any code Artifacts (Class or Method Names, Line Numbers, ETC.).
For Example, Consider The Following Stack TRACE:
Java.lang.RuntimeException: COULD NOT Load Data for Symbol IBM
At Boxpeeking.code.Yourcode.LoadData (Unknown Source)
At BoxPeeking.code.Yourcode.go (Unknown Source)
At Boxpeeking.Yourcode.ui.main 2.Run (unknown Source)
AT java.lang.thread.run (thread.java: 566)
Caused by: java.lang.RuntimeException: Timed Outat Boxpeeking.code.Yourcode.ConnectToDB (Unknown Source)
... 4 more
This should result in the GUI pop-up box in Figure 1, assuming that YourCode.loadData (), YourCode.go (), and YourCode.connectToDB () all have @Status annotations. Note that the order of the exceptions is reversed so That the user is given the most maxild information first.
Figure 1. Stack TRACE DISPLAYED IN An Error Dialog
Implementing this will require a few modifications to my existing code. First, to ensure that the @Status annotations can be seen at run time, I'll need to upgrade my @Retention again, to @Retention (RetentionPolicy.RUNTIME). Remember, @Retention controls when the JVM is free to discard annotation information. This setting means that annotations will not only be inserted into the bytecode by the compiler, but will also be accessible through reflection with the new Method.getAnnotation (Class) method.
Now, I'll need to arrange to receive notification of any exceptions that our code does not explicitly handle. As of Java 1.4, the best way to handle uncaught exceptions for a particular thread was to subclass ThreadGroup and add your new thread to a ThreadGroup Of this Type. However, Java 1.5 Provides Additional FunctionAn Instance of The UncaughTexceptionHandler Interface and Register IT for Either A Specific Thread, or for all threads.
Note: Registering for a specific exception would probably be preferable in this case, but there was a bug in Java 1.5.0beta1 (# 4986764) that prevented this from working Setting a handler for all threads, however, does work, so I '. Ve Done this as a workaround.
Now that we have a way to intercept the uncaught exceptions, they need to be reported to the user. In a GUI application, this is typically done by popping up a modal dialog box containing the entire stack trace, or perhaps simply the message. In this case, I want to display the message if any exception is thrown, but I want to provide a stack of @Status descriptions instead of class and method names. to do this, I simply iterate through the Thread's array of StackTraceElements, find the associated java.lang.reflect.Method object for each frame, and query it for a list of stack annotations. Unfortunately, only method names are provided, not method signatures, so this technique will not support overloaded methods with the same name (and different @ Status annotations) .example code for this approach can be found in the / code / 04_exceptions Directory in the peekinginside-pt2.tar.gz file (see reason ".
Sampling
I now have a way to turn an array of StackTraceElements into a stack of @Status annotations. This is actually more useful than it may seem. Another new feature in Java 1.5, thread introspection, gives us a way to get extract array of StackTraceElements from a currently running thread. With these two pieces of the puzzle, I can construct an alternate implementation of the JStatusBar from Part 1. Instead of receiving notifications when each method call takes place, the StatusManager can simply start up an additional thread responsible for grabbing a Stack TRACE AT REGULAR INTERVALS AND ITS State At Each Step. AS Long As This Interval is Short Enough That The User Does Not Perceive The Update Delay, this is Just As Good.
Here's The Code Behind Our "Sampler" Thread, Which TRACKS The Progress of Another Thread: Class StatusSample IMPLEments Runnable
{
Private thread Watchthread;
Public StatusSampler (Thread Watchthread)
{
THIS.WATCHREAD = WatchThread;
}
Public void Run ()
{
While (WatchthRead.isalive ()) {
// Get Stack TRAM The Thread.
StackTraceElement [] stacktrace =
Watchthread.getstacktrace ();
// Extract status msgs from stack trace.
List
StatusFinder.getStatus (stacktrace);
Collections.reverse (statuslist);
// Build A State from Status Msgs.
StatusState State = new statusState ();
Status s: statuslist) {
String message = s.value ();
State.push (Message);
}
// Update the current stat.
Statusmanager.SetState (Watchthread,
State);
// Sleep Until the next cycle.
Try {
Thread.sleep (Sampling_delay);
} catch (interruptedexception ex) {}
}
// RESET STATE
Statusmanager.SetState (Watchthread,
New statusstate ());
}
}
Compared to adding method calls, either manually or via instrumentation, sampling is much less invasive. I did not need to change any build processes or command-line arguments, or modify my start-up procedure at all. It also allowed me to control how much overhead is incurred simply by adjusting the SAMPLING_DELAY. Unfortunately, there is no explicit callback when a method call begins or ends. Other than the latency of the status updates, there's no reason that this code would need to receive callbacks at the moment. However, in The Future, I Could Add Additional Code To TRACK THE The Exact Run Time of Each Method. It wouldleleferences.
Example code to implement JStatusBar by means of thread sampling can be found in the / code / 05_sampling directory of the peekinginside-pt2.tar.gz file (see References) .Instrumenting Bytecode During Execution
By combining the sampling approach with instrumentation, I was able to come up with a final implementation that provides the best features of each. Sampling can be used by default, but methods that the application appears to be spending the most time in can be instrumented individually . This is a Time In response to the data collection...........................
To accomplish this, I'll create a new class, InstrumentationManager, which can be used to instrument and un-instrument individual methods. This will use the new Instrumentation.redefineClasses method to modify classes on the fly, while the code is executing. The StatusSampler thread, added in the previous section, will now have the additional responsibility of adding any @Status methods that it "sees" to a collection. It will periodically pop off the worst offenders and feed them to the InstrumentationManager to be instrumented. This allows The Application To Track Each Method's Start and End Times More Pregraise.
One of the problems with the sampling approach discussed earlier is that it can not distinguish between methods that take a long time to run and methods that are called many times in a tight loop. Since instrumentation is adding a fixed amount of overhead to every method call, it would be useful to skip over methods that are called very frequently. luckily, we can resolve this with instrumentation. In addition to simply updating the StatusManager, we will also maintain a running count of the number of times each instrumented method has been called. If this count exceeds some threshold (meaning that it is too expensive to maintain information for that method), the sampling thread can permanently undo the instrumentation of that method.Ideally, I would have liked to store the call count of each method in New Fields Added to the Class During Instrumentation. Unfortunately, The Class Transformation Mechanism Added in Java 1.5 Does Not Allow this; No Fields Can Be Added or Removed. INSTEAD, I 'Ve Stored this Information in A Static Map of Method Objects in The New CallCounter Class.
.
Summary
Figure 2 Presents a Matrix Showing The Features and Costs Associated with each of the example That I've provided.
Figure 2. Analysis of Instrumentation Approaches
As you can see, the Dynamic version is a good compromise between the other solutions. Like all of the examples that used instrumentation, it provides explicit callbacks when a method starts or stops, so that your application can track exact run times and provide immediate feedback to the user. However, it is also able to un-instrument methods that are called too often, so it does not suffer from the same performance problems that the other instrumentation solutions do. There are no compile-time steps involved, and it does NOT Add Any Additional Work to the class-loading process.future directions
There are a number of additional features that could be added to make this project more practical. Perhaps the most useful feature would be dynamic status messages. The new java.util.Formatter class could be used to provide printf-like pattern substitution into the @ Status Messages. For example, anovotation of @status ("Connecting TO% S") IN OUR ConnectToDB (String URL) Method Could Actually Report The URL AS Part of The Message.
With source-code instrumentation, this would be trivial, as the Formatter.format method I would like to call uses variable arguments (more black magic added in Java 1.5) The instrumented version would look something like this.:
Public void connectiontoc (String URL) {
Formatter f = new formatter ();
String message = f.Format ("Connecting TO% S", URL);
Statusmanager.push (Message);
Try {
...
} finally {
Statusmanager.pop ();
}
}
Unfortunately, this black magic is implemented entirely in the compiler. In bytecode, Formatter.format takes an Object [], and the compiler explicitly adds code to box each of the primitive types and assemble the array. Until BCEL catches up, I would ' ve had to re-implement this logic if I wanted to use bytecode instrumentation for this task.Since this would only work for instrumentation (where the method arguments are available) and not for sampling, you may want to instrument these methods at startup, or At Least Have The Dynamic Implementation for Any Methods With Substitution Patterns in The Message.
You could also track the start times of each instrumented method call so that you could more accurately report the running times of each. You could even keep historical statistics on these times and use them to seed a real progress bar (instead of the indeterminate version I Used). THIS CAPABILITY WOULD GIVEY A Good Reason To Instrument Methods One At A Time, Since The Overhead Involved in Tracking Any Individual Method Would Be Much More Signific.
You could add a "debug" mode for the progress bar, which reports on all method calls that show up in sampling, regardless of whether they have a @Status annotation. This would prove invaluable for any developers who need to debug a deadlock or performance Issue "in the field." in Fact, Java 1.5 Also Provides a programmatic API to ITS Deadlock Detection, and this could be used to make the progress bar turn.
There's probably also a market for a "fully baked" version of the annotation-based instrumentation framework that I've built in this article. A single tool that allowed bytecode instrumentation at compile time (via an Ant task), startup time (with a ClassTransformer, and during execution (Using Instrument) Would No Doubt Be Invaluable for a Few Other Projects.conclusions
As you can see by these few examples, meta-programming can be a very powerful technique. Reporting on the progress of long-running operations is just one possible application of this technique, and our JStatusBar is just one medium for communicating this information. As we've seen, many of the new features in Java 1.5 provide enhanced support for meta-programming. in particular, the combination of annotations and run-time instrumentation provides for a very dynamic form of attribute-oriented programming. These techniques can be used To Go Far Beyond What Existing Frameworks Like Xdoclet Provide.