Monday, June 15, 2009

Shutdown hook in Groovy... Inner Classes in Groovy

Groovy doesn't support Inner classes directly. I was in a hurry to implement a shutdown hook in Java so I came accross the groovy workaround

I had to tweak the script slightly to get it to work for the shutdown hook (see below).

To implement the shutdown hook in Java a Thread instance is passed to the addShutdownHook() method of the Runtime instance.

In Java we could create an Inner class that extends Thread, or that implements Runnable.

In Groovy we must create a Map. The Map contains a list of key/ values. These correspond to method names (key), and method implementations (closure). For this case the closure will represent the Thread that we pass to the Runtime.addShutdownHook() method. Therefore we are implmenting the run() method, so the key in the map must be run().

The ProxyGenerator is then used to dynamically add the interface to the close. Finally since Runtime.addShutdownHook() expects a Thread instance (not simply a class that implements Runnable) ,we must add the Thread.class to the call to ProxyGenerator.instantiateAggregate().

def shutdownClosureMap = [run: {
println "Shutting down";
def interfaces = [Runnable]
def shutdownListener = ProxyGenerator.instantiateAggregate(shutdownClosureMap, interfaces, Thread.class)


No comments: