Monday, February 16, 2009

Java + Groovy

If you do not need a blazing rocket-science performance, but just need to toss up some prototype or even production software in Java platform, but you really-really-really do not waste time on Java language verbosity, you may consider using Groovy as a dynamic language extension to the Java platform.

Let's do something silly, but to see how the things are interacting between each other. For example, let's read our "/etc/passwd" into a list and display a first element of it from a plain Java, omitting an empty lines and/or commented ones. :-) Here how it is done in NetBeans IDE:
  1. Make sure Groovy support is in your NetBeans 6+. Usually it is there out of the box, but maybe some plugins must be installed. Check it by Plugin Manager, navigating to "Menu→Tools→Plugins" and see maybe you need some tweaks in Preferences for Groovy specifically.
  2. Create new Java Application project. Let's call it "JavaAndGroovy".
  3. In your package, called now "javaandgroovy" create a Groovy Class. Since it is an example, let's call it "Grovample".
Great. Now is a time to read the file with one codeline, as a text and return a list of the lines. Here you go:
package javaandgroovy

class Grovample {
def readfile(filename) {
List data = []
for (line in new File(filename).readLines()) {
line = line.trim()
if (line && !line.startsWith("#")) {
data.add(line)
}
}

return data
}
}
Now, to use this class in the plain Java, just... use this class! Like this:
package javaandgroovy;
import java.util.List;

public class Main {
public static void main(String[] args) {
List passwd= (List) new Grovample().readfile("/etc/passwd");
System.out.println("Lines: " + passwd.size());
if (passwd.size() > 0) {
System.out.println("First line: \n" + passwd.get(0));
} else {
System.err.println("Well, you're on Windows. :-P");
}
}
}
As a result, I am getting the following output:
Lines: 40
First line:
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
Now, let's look how the distribution looks like. Press "Clean and Build" button or simply navigate to your project directory in the terminal and run "ant" command. In a "dist" subdirectory, here is the following tree:
.
./JavaAndGroovy.jar
./lib
./lib/groovy-all.jar
./README.TXT
File "groovy-all.jar" has a weight of 2.7Mb. Not so small for very tiny apps, but not so big for bigger ones. You might consider put this lib in your GlassFish somewhere, in order to do not deploy it every time with your WAR/EAR. :-)

Keep in mind: Groovy is significantly slower than plain Java. Really slow. Check out it how much slower. Still, it does not means that we can not use Groovy for many-many tasks around and simplify our Java code.

Happy Grooving! :-)

1 comment:

Christian Schenk said...

You're right: although Groovy is solwer than plain Java you shouldn't stop using it - in most cases you won't notice the performance penalty.