Archive for the ‘Java’ Category

Groovymonkey

Sunday, May 18th, 2008

We have introduced Groovy in or product about a year ago as a scripting mechanism for power users. A year later it became a key component and we use it everywhere.
It is important to understand that our developers do not write Groovy code, it is only used as a way for end-users to extend the behavior of the application.

It would be too complicated to explain the product I am working on and it is also more interesting to think about what can be done rather than what we have done.
Imagine what you could do if you could write scripts in your email application. The application could be fully written in Java and you as an end-user could write scripts that act like filters on your inbox but could do much more than moving emails to folders.
Isn’t it exciting? Groovy enables in your application what Greasemonkey does for Firefox.

You can write Groovy code just like you write Java. It has classes and methods just like Java. In fact, you could rename a .java into .groovy and in many cases it will work without changing anything.
Groovy also works in scripted mode. It means that you can execute a piece of code out of a class/method context.
The scripted mode can be invoked from Java. That is the mode that you would use to implement end-user scripting.

    new GroovyShell().evaluate("System.out.println(\"Hello World\");");

This very simple example shows how easy it is to run a script but also shows the seamless integration between the script and your application. The System.out referenced in the script is THE Sytem.out.

The script would not be very useful without input.
Here is how you you would pass variables:

  GroovyShell shell = new GroovyShell();
  shell.setVariable("message", "Hello World");
  shell.evaluate("System.out.println(message);");

And you can get data back either by using getVariable() or using the returned value:

  GroovyShell shell = new GroovyShell();
  shell.setVariable("message", "Hello");
  Object o = shell.evaluate("return message + \" World\";");
  System.out.println(o);


There is much much more to write about Groovy. The language is a really nice extension to Java. I used Java-like syntax in the examples but Groovy extends Java and allows a lot of shortcuts that could have been used in the examples. Semicolons are optional, println() can replace System.out.println(), variables can be referenced inside strings ("Hello $name").
I have only written a dozen of scripts and I am already hooked to closures.

If you do not know Groovy, I would encourage you to read about the language and if you are doing Web development, you should also have a look at Grails.

The Beep Breakpoint

Sunday, January 28th, 2007

Sometimes you would like to know how often a method is called. You don’t need to know the exact number but just have a feeling of how often it is.

The traditional technique would be to add a System.out.println() but that means that you have change your source file, recompile, play with your application while keeping an eye on the console and then remove your trace code. If the code you want to watch is in a library or in the JDK, then it becomes much harder.

There is an easier way…

I remember an article in Dr Dobb’s journal that described how to analyze the performance of a program using an oscilloscope. The paper described how to emit a signal on the RS232 port on which you would connect the oscilloscope.
The technique described here is similar but don’t worry, you will not need an oscilloscope, we will just use a nice feature of JDeveloper’s debugger, the “Beep Breakpoint”

Imagine your Swing application displays a JTree and you would like to know how often the tree’s cell renderer is invoked.

  • Go to the DefaultTreeCellRenderer class and put a breakpoint in the getTreeCellRendererComponent() method. JDeveloper may warn you about debugging being disabled in that class and offers you to change the setting. Click Yes and clear the two fields you see in the dialog.
  • Edit the breakpoint properties (right-click the breakpoint icon in the margin and select Edit…)
  • Switch to the Actions tab and only leave the “Beep” box checked:
    Edit Breakpoint

  • Press the Debug button…

Now every time that line is executed you will hear a beep. If the line is executed a lot you will hear a lot of noise.

There is another interesting usage of that technique. You may want to verify what parts of your application exercise a piece of code. Finding the usages of the method is not always convenient because many paths can lead to the method. Using a simple breakpoint does not work because it would interrupt the application for usages you did expect.
Put a Beep breakpoint in the method you want analyze and test your application. You will hear a beep every time the method is executed and it will be very easy to detect what part(s) of the application unexpectedly calls the method.

The Beep Breakpoint is not the only advanced feature of JDeveloper’s debugger but it certainly is the most annoying for your coworkers.

The Pair class

Saturday, January 20th, 2007

This article describes a little utility class that I have found very useful in different occasions.
You may have already seen the Pair class in other languages or in libraries without realizing how helpful it can be in Java.

The Pair class holds two objects, first and second. first defines the behavior and second holds a reference to an associated object:

  • The toString(), equals() and hashCode() methods return the values of the first element
  • Pair implements Comparable and the compareTo() returns the comparison of the first elements.
public class Pair implements Comparable {
    public Object first;
    public Object second;

    public Pair() {
    }

    public Pair(Object first, Object second) {
        this.first = first;
        this.second = second;
    }

    public Object getFirst() {
        return first;
    }

    public void setFirst(Object first) {
        this.first = first;
    }

    public Object getSecond() {
        return second;
    }

    public void setSecond(Object second) {
        this.second = second;
    }

    public String toString() {
        return first.toString();
    }

    public boolean equals(Object that) {
        return that.equals(first);
    }

    public int hashCode() {
        return first.hashCode();
    }

    public int compareTo(Object thatObject) {
        final Pair that = (Pair) thatObject;
        final Comparable thisComparable = (Comparable) this.first;
        final Comparable thatComparable = (Comparable) that.first;
        return thisComparable.compareTo(thatComparable);
    }
}

Replacement for CellRenderer

When you add you own objects to a JList or JTree, Swing uses the toString() method of your object to get the label to display.

This is not always convenient. You may not be the owner of the object. If you want to display a list of java.awt.Color objects for example, you do not have the liberty of adding a toString() method to the Color class.
You may want to use the toString() method for you own debugging purpose. Most debuggers today allow you to display the toString() value in the data window.
Sometimes the same object will be displayed differently depending on the context.

The alternative would be to write a CellRenderer but you know the cost of a class and writing a cell renderer just to define the label of the objects might be an overkill.

This is where the Pair class becomes handy: add Pairs to the list. The first element will be the label and the second is your object.
Since Pair implements Comparable, it can even be used to sort the list.
The following example illustrates how to add objects to a JList but using a different text than the toString() of the object. The example takes advantage of the HTML capability of the Swing components to show the last name in bold.

        List<Person> persons = Arrays.asList(
                new Person("Adrian", "Monk"),
                new Person("Disher", "Randall"),
                new Person("Leland", "Stottlemeyer"),
                new Person("Sharona", "Fleming"),
                new Person("Natalie", "Teeger")
        );

        final Pair[] temp = new Pair[persons.size()];
        for (int i = 0; i < persons.size(); i++) {
            final Person person = persons.get(i);
            final String label = "&lt;HTML&gt;&lt;B&gt;" +
                                 person.getLastName() +
                                 "&lt;/B&gt;, " +
                                 person.getFirstName();
            temp[i] = new Pair(label, person);
        }
        Arrays.sort(temp);

        final JList list = new JList(temp);
        final JLabel label = new JLabel();
        final JPanel panel = new JPanel(new BorderLayout());
        panel.add(list);
        panel.add(label, BorderLayout.SOUTH);

        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    final Pair selectedPair = (Pair) list.getSelectedValue();
                    final Person person = (Person) selectedPair.second;
                    label.setText("Your selection: " +
                                  person.getFirstName() +
                                  " " +
                                  person.getLastName());
                }
            }
        });

And here is what it looks like:

Pair Demo

The source code is available here.

Class Size

Saturday, January 20th, 2007

Are you concerned about the memory your java application uses?

You probably have already removed those unused methods or fields or variables, you have used an integer field to store flags instead of using booleans, you have changed an algorithm to not use an intermediate ArrayList, …

There is one area that is usually overlooked when writing an application which is the size of classes. Once a class is loaded in memory, it will stay in memory until your program terminates and classes have a memory price tag that should not be ignored.

To determine the cost of a class, I wrote a small application that generates thousands of similar classes plus one that calls them all.
The generated application first waits for the user to press ENTER in the console. This gives you the time to look at the process in the Task Manager and write down the memory size of the process.
Once you press ENTER, the application invokes 10.000 classes and then pauses again. Go back to the Task Manager, record the new memory size and do the maths.

Here is an example of a generated class:

package generated.p4;
public class C2017 {
    private String a;
    public void setA(String a) {
        this.a = a;
    }
    public String getA() {
        return a;
    }
    public static void foo(){
        final C2017 a = new C2017();
        a.setA(a.getA());
    }
}

Depending on the VM you choose to run the application, the memory consumed by each class varies betweeen 2Kb (-client) and 1.7Kb (-server).

Listener Pattern

Knowing that any class will cost approximatively 2Kb, you may want to revisit some of the patterns you use when writing code.
A typical example is the dialog listeners.
If you usually write code like this:

public class MyDialog {

    private void init(){
        JButton addButton = new JButton("Add...");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                whenAdd();
            }
        });
        JButton removeButton = new JButton("Remove...");
        removeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                whenRemove();
            }
        });
        JList list = new JList();
        list.addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                whenSelectionChanges();
            }
        });
    }

    private void whenAdd() {
    }

    private void whenRemove() {
    }

    private void whenSelectionChanges() {
    }
}

You may want to switch to a pattern that only uses one listener:

public class MyDialog {
    private JButton addButton;
    private JButton removeButton;
    private JList list;
    private Listener listener = new Listener();

    public BetterDialog(){
        addButton = new JButton("Add...");
        addButton.addActionListener(listener);
        removeButton = new JButton("Remove...");
        removeButton.addActionListener(listener);
        list = new JList();
        list.addListSelectionListener(listener);
    }

    private void whenAdd() {
    }

    private void whenRemove() {
    }

    private void whenSelectionChanges() {
    }

    class Listener implements ActionListener, ListSelectionListener {

        public void actionPerformed(ActionEvent e) {
            Object source = e.getSource();
            if (source == addButton) {
                whenAdd();
            }else if (source == removeButton) {
                whenRemove();
            }
        }

        public void valueChanged(ListSelectionEvent e) {
            Object source = e.getSource();
            if (source == list) {
                whenSelectionChanges();
            }
        }
    }
}

The revisited version may look less efficient because the code is a bit longer and the widget are stored in fields but in reality this version uses 2 classes instead of 4 and will therefore save about 4Kb of memory, the resulting byte code is smaller by about 10% and even the small memory overhead to store the widgets will eventually be reclaimed by the garbage collector.