Archive

Archive for November, 2007

Name Your Syncrhonization Objects

November 12th, 2007 No comments

A not-used-enough feature of Java is the ability to set the name of a thread. Simply pass the name to the thread’s constructor, or call the Thread.setName() method. The nice thing about this is that when you’re looking at the thread list in a debugger, the names of the threads will be displayed rather than some random identifier generated by the JVM or debugger. This is a boon for sanity. But what about synchronization objects?

As Joshua Bloch recommends in Effective Java, it’s a good idea to favor the private lock object idiom over the more typical practice of sprinkling your methods with synchronized keywords. Now, most examples you’ll find just create a new Object for the private lock:

   private Object lock = new Object();

That’s fine, but some debuggers, especially Eclipse will also show the locks that each thread holds and which lock they’re waiting for. If you just use a plain old Object, the debugger’s output won’t be very descriptive. Since the debugger just uses the toString() method to display the lock object, we could just use that to give the lock a name. I wish their was an object with the toString() method already implemented…

   private Object lock = new String("My Lock");

The important thing here is to make sure you create a NEW string instance. If you just use a string literal, it will be taken from the string pool and, if you’re unlucky, your lock may get used and possibly locked by someone else. Not very private.

Anyway, the result is nice, readable lock names that really help when tracking down deadlocks.

Categories: concurrency Tags:

Java Package Versioning

November 8th, 2007 No comments

Once again, I stumble onto some feature of the Java platform that I had no idea existed. Today, while researching various ways to store version and build information in jar files, I found this article on Java Product Versioning.

The main idea is that there are now interfaces for accessing special tags in your manifest file. Obviously, the ability to read manifests has been around for a while, but all of the methods I’ve seen were a little hacky. They all involved figuring out the path to your jar, often by parsing the class path and then extracting the manifest from it. This is necessary because, depending on class path order, just asking for ‘/manifest.mf’ with the resource interfaces won’t necessarily get you your manifest.

This article describes the Package class which knows which manifests go with which classes. It also provides methods for accessing the following manifest properties:


Specification-Title: “Java Utility Classes”
Specification-Version: “1.2”
Specification-Vendor: “Sun Microsystems Inc.”
Package-Title: “java.util”
Package-Version: “build57”
Package-Vendor: “Sun Microsystems. Inc.”

etc…

Clearly, this has been around for a while. Why does it always take so long for me to find out about these things? Is this not as useful as it seems?

Categories: java Tags:

Scripted Data Sources with BIRT

November 1st, 2007 4 comments

I recently started experimenting with the BIRT reporting engine for Java. It seems pretty powerful, well-designed, and has a nice report design tool implemented in Eclipse. Since the project I’m working on doesn’t have a database, I decided to use BIRT’s scripting data sources. These allow you to create a (hopefully) small JavaScript glue layer between the reporting engine and your plain old Java objects. The purpose of this post is to cover some of the gotchas I’ve encountered so far.

The basic idea is that you implement a few JavaScript callback methods that feed row-like back to the reporting engine. BIRT uses Mozilla’s Rhino JavaScript engine. Since the typical use case for BIRT is a database backend, the documentation for the scripting interface seems harder to come by. The FAQ helped, but didn’t answer all of my questions.

First, all of the examples retrieve their “model” from a static factory method called from JavaScript. This isn’t that realistic. How do I pass my model in to the JavaScript? Or at least a parameter like a filename? I think part of the reason all the examples take this approach is so that it’s possible to run the report at design time with the preview window. I did some digging and eventually found the right calls:

MyModel model = ...;
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
Map parameters = new HashMap();
parameters.put("model", model);
task.setParameterValues(parameters);

Cool. Now my model’s being passed to the engine. But wait. How does BIRT find my classes? I know it’s built on top of Eclipse which means the classpath is not as simple as you’d like. In some examples I found, you have to manually copy your compiled class files to a directory in one of the BIRT plugins. Uggh. This is a pain, but acceptable for deployment. But during development? I might as well go back to C++ if I want to waste that much time.

Some more searching dug up this FAQ question. It lists too yucky solutions and then has a tacked on snippet of code that looks promising.

 
config = new EngineConfig();
HashMap hm = config.getAppContext();
hm.put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY,MyClass.class.getClassLoader());
config.setAppContext(hm);

However, I guess I think this is for the version of BIRT I’m not using because it doesn’t work. Some more digging and I come up with this:

IRunAndRenderTask task = engine.createRunAndRenderTask(design);
HashMap contextMap = new HashMap();
contextMap.put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY,
                      MyModel.class.getClassLoader());
task.setAppContext(contextMap);

I guess the app context stuff moved from the task to the engine at some point. Anyway, now we can finally try it out. I set up my open callback in Java and… wait, how do I actually get to my model in the JavaScript code? This wasn’t too tricky to figure out. The parameters passed to the engine above are passed to the JavaScript code in a global (?) parameter aptly named params:

model = params["model"];

Nice. Now I write some more code to call some methods on the model and run it and… NullPointerException. This is where I was stuck for a little while. I thought that I had screwed up the class loader stuff or something so I fiddled with that stuff for a while. Eventually, when I was about to give up, I stumbled upon this bug report which, although it doesn’t mention a NullPointerException, does mention a “display name” which I had noticed references to while poking around in the debugger after my crash.

The trick is that the params variable in JavaScript doesn’t hold just my model, but an extra wrapper object with a display name and value is stuck in there. I revise my code to look like this:

model = params["model"].value

and voila, I run it again and my report is generated as expected.

Hope this is helpful to someone else out there.

Categories: birt, java Tags:

The Eclipse Reconciler

November 1st, 2007 5 comments

One aspect of implementing a text editor in Eclipse that I’ve found to be tricky is the reconciler. In this post, I’ll detail some of the lessons I’ve learned. I’m assuming you’ve gotten as far as creating a basic editor. The reconciler is a background process in your editor responsible for updating your model when the user takes a break from typing. The kinds of things it should update are:

  • Elements displayed in the outline view
  • Error markers
  • Folding regions

Some editor programmers don’t seem to know that the reconciler even exists. They usually take one of two approaches: update the entire model on every keystroke or update the model only when the user saves. Neither of these is very satisfying, especially for users familiar with editing Java in Eclipse. The former approach leads to poor performance on large files. The latter requires the user to save constantly to find out whether errors exist or get an up to date outline.

So, how does the reconciler work? The reconciler runs as a background thread in Eclipse. It sets a timer which will trigger a reconcile whenever it expires. Each time the user types a keystroke, the timer is reset. In this way, the user can type a great deal of text without being interrupted by the reconciling process. Once the user pauses, as all humans must, the reconciler’s timer expires and the model is updated.

Creating a Reconciler

Eclipse uses the strategy pattern to separate the timer/keystroke logic from the details of updating your model. The MonoReconciler is the simplest implementation of the timer/keystroke logic. It is configured with an instance of IReconcilingStrategy which is responsible for updating your model, i.e. you implement this interface.

The basic procedure for setting up your reconciler and reconciling strategy are:

  • Implement IReconcilingStrategy. You’ll want to implement the non-incremental version of reconcile(), i.e. reconcile(IRegion partition). More on this below.
  • In your editor’s SourceViewerConfiguration, override getReconciler() to return an instance of MonoReconciler, initialized with an instance of your reconciling strategy and isIncremental set to false

That’s it. Now when your editor is created, your reconciler will be initialized and the reconcile() method will be called whenever the user modifies the document. I usually store a reference to the editor itself in the strategy object.

The Reconciler Runs in Its Own Thread!

It’s important to always remember that the reconciler runs in its own thread, as with most stuff in Eclipse. It’s safe to access the document, but there are few other things you need to keep in mind:

  • All SWT/JFace operations must be executed in the UI thread. So, if you want to update your outline view after a reconcile, you’ll have to use Display.asyncExec().
  • Your model also has to be thread safe. If it’s being update in the reconciler thread and read from in the UI thread to update the outline view, you’re going to need some synchronization.
  • It is safe to add warning and error markers to the file from the reconciler thread

If your model is simple enough, one simple solution to this problem is to have the reconciler construct an entirely new model each time it runs and then pass it on to the editor with Display.asyncExec(). This way there are no shared objects between the threads and thus, no syncrhonization problems.

What if the user doesn’t start typing right away?

After you’ve implemented your reconciler, everything will seem great. Great until you (or a user) decides to just view a file without editing it. They’ll find that their outline view is not updated. Same with folding ranges, etc. The problem is that your reconciling strategy is not run until the document is actually modified. Go figure. If only there was a way to tell the reconciler, “Hey, how about an initial reconcile pass on the document right when it’s opened?”.

Fortunately, a friendly Eclipse programmer also thought of this question. Rather than implementing IReconcilingStrategy, try IReconcilingStrategyExtension. This adds an initialReconcile() method where you can do an … well, you get the idea.

What about the incremental reconciler?

If you poke around in the reconciler interfaces a bit you’ll notice there are actually two modes of operation. The non-incremental mode simply tells you that the document has been modified with little additional information. The incremental mode tells you about what’s changed in the document each time that reconcile() is called. It tells you when text has been added or removed and from where in the document. That sounds pretty useful!

On my last Eclipse editor project, I wanted to take advantage of this. If I knew which part of the document has changed, I could just reparse that section and update the affected model elements. I actually foolishly went through all the trouble of implementing this logic and then gave it a try. Things did not work as I expected. There is a fatal flaw in the incremental mode: By the time the reconciler is called, the document may have been modified further so all the modification information is provides is basically useless!

I believe this is caused by two factors. First, because it is multi-threaded, it’s hard to lock the document and still maintain the “update in the background” semantics of the reconciler. Second, the incremental reconcile() method only provides information about a single modification, i.e. an insert or delete in the document. So if the user does the classic “insert character + down arrow” editing technique to say comment out a bunch of lines, the reconciler will get called for each individual change, but the document will already contain all the modifications when the first reconcile call is made. D’oh.

When I realized it works like this, I did a bunch of searches on Eclipse newsgroups, google code, etc. I came to the conclusion that either no one has ever actually used the incremental reconciler, or they have and then silently slunk back to the non-incremental version when the found this fatal flaw.

If I’m wrong about this, I’d love to hear why!

Categories: eclipse, java Tags: