Archive for November, 2008

How to use Groovy without management finding out

November 20, 2008 5 comments

I hang out with Ruby guys and gals when I can. These folks are such a blessing to my brain. If you don’t have Ruby friends, find some. Google for “yourcity ruby brigade” to find a Ruby user group in your area.

I’ve often heard Ruby friends talk about utilities they wrote in Ruby that essentially generate boilerplate Java code, and I used to shudder at the thought.

I always figured “You have a great language that can do so many yummy things, why are you using it to write icky code!?”

I think I’m beginning to understand now: The icky language (sorry for the blasphemy, but yes, I mean Java) runs faster. It’s also more likely to be accepted by the governors in your projects. If you don’t know what I mean by governors, they’re the poor folks that take the heat and lose bonuses when stupid geeky experiments with unproven technologies ruin a project. These folks love the status quo. And bonuses. Your geeky technologies pose a threat to both.

Groovy noobs and doubters ask “How can I get management to approve using Groovy in my project?” Well, you can write Groovy scripts that no one needs to know about. Write scripts that generate Java code.

I’m not completely off my rocker.

Grails does some cool code generation to write Groovy views and controllers based on your tiny li’l POGO domain classes. It’s so awesome not to have to write boilerplate code or have to start everything from scratch. I can literally create an entire CRUD webapp in a couple minutes, even with a couple beers in me (which, for the record, only happens at home on my own time – I swear). Why code generation is awesome: Doing tedious code manually from scratch is like a coding limbo… never really touching heaven or hell but it passes the time.

Code generation good. Hulk like code generation. Tedious code make Hulk angry! Hulk smash!!!!!

Just to play around and set my first goal low, I challenged myself to write a Groovy script that creates a Java constructor. All my favorite IDEs do this for me already, but I’m not going to let practicality get in the way of fun… certainly not when I’m coding on my own time at home! Time to play!!!

class Person{
  private String firstName;
  private String lastName;
  private int age;

void constructor(Class clazz){
  def props ={
    // filter out the properties I do not want
    !it.toString().contains("static") &&
    // I want the property type and name
  // dump out the constructor!!! yay!!!
  print " public ${}("
  print props.collect{"${it[0]} ${it[1]}"}.join(', ')
  println "){"
  props.each{ println " this.${it[1]} = ${it[1]};"}
  println " }"



All I have to do is paste in a new class definition like I did with the Person class and call my dandy new constructor() method, passing to it the name of my class. In Groovy I don’t have to say Person.getClass() or even Person.class – just plain ol’ Person is good enough.

My console dumps out:
  public Person(String firstName, String lastName, int age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;

Not too shabby.

Keep in mind the DRY principle. Your first priority is to write Java code without any duplication. In most cases you can avoid duplication by simply following basic OO principles.

If, however, boilerplate code seems like a necessity, consider generating it.


Groovy Strings n Things

November 17, 2008 4 comments

I’d like to take a moment to speculate on one of our previous posts,  A quirk in Groovy maps and GString coercion.

This post brought up a good example of some buggy behavior in Groovy when it comes to GStrings and Maps.  However, I don’t think the problem is in the Map, but in mixing/matching java.lang.String’s with groovy.lang.GString’s, and in particular on existing Java class methods that expect Strings.  Taking the two examples from the previous post..  

Exhibit A:

println map[“$aVar”] //still good, this outputs x.

println map.get(”$aVar”) // oh snap! this outputs null!


Exhibit B:

println ‘a’ == “$aVar” // true

println ‘a’.equals(”$aVar”) // double snap!! it’s false!!

I think there’s a pattern..  

In the first part of both of these example, we’re taking advantage of the operator overloading that Groovy provides and mix/matching java.lang.Strings and groovy.lang.GStrings, which seem to play nicely together in those cases.  It appears that the GStrings are being evaluated before being coerced into Strings.  The coercion must be happening at runtime for the dynamic GString to have it’s $value translated and put into the resulting String.

However, in the later case of both of these examples, we’re calling existing methods on existing Java classes (java.util.Map and java.lang.String).   These methods take Strings not GStrings.  In these cases, it looks like Groovy still coerces these GStrings into Strings, but my hunch is that it must do so at compile time in order to play nicely with statically typed Java methods on statically typed java objects.  This would mean that it wouldn’t have enough information at that time to replace the $aVar with it’s dynamic runtime value and therefore doesn’t know what else to do but use the literal String value.

This is all speculation of course, but this model makes sense of what we’re seeing here.  Is there anyone who knows enough about the internals of Groovy to confirm or deny this speculation?

Tags: ,

The Executor Framework

November 8, 2008 7 comments

It’s great. It allows you to handle concurrency in Java (or Groovy) without directly using the Thread class.

I first heard about the executor framework in Effective Java (Second Edition) (Item 68: Prefer executors and tasks to threads) and became really interested in it, decided to investigate further, and gave a presentation on it for my coworkers.

The Executors class (new in Java 5) provides a bunch of static factory methods for creating executors. With an executor, you can submit a task (Runnable or Callable) that will be performed by that executor. Here’s an example:

ExecutorService executor =

As you can probably guess, this will create an executor which has a single thread. That thread will take the runnable and call its run() method. If the execute method is called multiple times, each runnable that’s passed in to the method will be placed on a queue. When the executor’s thread is available, it’ll pull the first runnable off the queue and run it. When that one finishes, it’ll grab the next one, and so on.

If a single thread isn’t enough, you can do the following:

ExecutorService executor = Executors.newFixedThreadPool(5);
for (Runnable runnable : runnables) {

This would create a thread pool with 5 threads that can execute the runnables. Again, the execute method places each of the runnables on a queue, and whenever one of the 5 threads is available, it pulls the runnable off the queue and runs it. That’s it! It’s so simple.

If you want to schedule your tasks to run at certain intervals, you can do this:

ScheduledExecutorService executor =
executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.MINUTES);

This will submit a task to be executed every minute. The single thread in the executor will run the task right away, and then again every minute. The ‘0’ above indicates the initialDelay – that is, the number of units to wait before the first invocation of the runnable. The ‘1’ indicates the number of units between each invocation of the runnable. And, of course, TimeUnit.MINUTES indicates that the units for the ‘0’ an ‘1’ should be minutes.

If you’re using Groovy, it’s even easier because you don’t have to implement Runnable – you can just pass a closure to the executor (since Closure implements Runnable).

There’s no longer a reason to create threads directly in Java. The language now provides an easy way for you to run tasks in separate threads without having to micromanage them.

Chain those Crazy Groovy Closures with Currying, Case Study: Mimicking Intercepting Filter

November 3, 2008 8 comments
Below is a post I wrote a little while back but never published. If you’re wanting to learn better how closures work or how to use currying, this can be a really fun exercise. I didn’t publish this earlier because I didn’t want to encourage anyone to implement this in production code as if this were some kind of pattern.
Please, treat this post merely as something fun to play with. Do not use this in production code. Please, I beg you. Think of the kittens.
– Peabody
A week ago Josh and I wanted to chain a bunch of behaviors together in Groovy.
One of the first possible solutions that popped to mind was the very flexible Intercepting Filter pattern common to Java EE web applications.
I think we ended up deciding, for what we actually needed, this neato solution wasn’t the best fit. But the process was extremely rewarding and sharing it might help some folks get a better feel for how powerful closures can be and get a little more familiar with currying.
Here’s the basic pattern diagram for the Intercepting Filter from Sun’s site. The important parts here are the Filters One, Two, and Three. We want to be able to call a chain of these filters and each filter will be responsible for doing any pre or post processing and likely call the next filter in the chain at some point in the middle.
Figure 7.1
Here are our three filters. They’re simply closures that accept another closure as an argument. In JavaEE, the Intercepting Filter gets added to a chain of other filters. Each one can run some pre-processing logic, call the next item in the chain, then call some post-processing logic before returning. In our closures, the pre and post processing both simply output something to the console and, in between those, we call the next item in line with The c={} argument defaults our c variable to an empty closure if no other closure is passed in as an argument. 

def one = { c={}->
  println "one*";;  println "*one"
def two = { c={}->
  println "two*";;  println "*two"
def three = { c={}->
  println "three*";;  println "*three"

Note to Reader: Please copy this code into your GroovyConsole as you follow along. It will be much, much more fun for you that way. ;)
So now I can call one of my fancy new closures like I would a method.
Try this:
I called the two closure with no parameters. This worked even though the signature for two has an expected variable of c. It did not complain because I declared it c={} which means that it will just default to an empty closure if I don’t supply one.
Let’s call our two closure again now but supply it with another closure as an argument.
Try this:
two{ println ‘hey there!’ }
hey there!
That worked pretty well. Now let’s try combining the closures.
Try this:
That’s pretty sweet. But we might end up needing a handful of behaviors to run through and that curly brace syntax can become messy quickly.
We know that with a little currying we can build all of my little closures into a bigger closure.
def myChain = one.curry(two.curry(three.curry({})))
Then we can call that one chain by itself.
But we want to dynamically build that chain. We should be able to call it like:
chain([one, two, three])
Or if we had more closures:
That allows us to pack a lot of behavior into a small amount of code and we can mix, match, and put these behaviors in any order we want.
Here’s a little method to help us with that.
def chain(List commands){
  def chainToCall = {}
    chainToCall = command.curry(chainToCall)
Give it a try! :)
PS – Here is an even shorter version of that chain method by using inject. One of my next posts to Inside the Machine will explain inject in greater detail. I hope you can see that inject allows much more succinct code.
def chain(List commands){
  commands.reverse().inject({}){chainToCall, command->