Saturday, December 12, 2009

Java 5 + GPars: Throttling Action Processing

An interesting question came up on the GPars mailing list today: In a system that generates events, what is the best way to throttle back event processing to one event per second? I thought about an answer... then thought some more... and finally decided to write it all up in this blog post. The example uses Groovy and GPars, but it is easily adapted to a generic Java solution. Don't let the actors scare you! (or the lack of semi-colons, for that matter).

The example is the classic "Sleeping Barber" problem (I hadn't heard of it either). Basically, there is a barbershop. The barber is asleep. Customers walk into the waiting room periodically, and the barber wakes up to give each of them a haircut. When he's done he returns to his slumber. It's a lesson in reaction: something is asleep, then awakens to do some work, then returns to sleep.

The GPars docs provide a decent Actor based solution to this problem: there is a waiting room and a barber, and both are actors. When the barber is free, a customer from the waiting room is moved into the barber's chair. The barber and waiting room communicate via actor messages. But what if our barber is a bit of a diva, and no matter how busy the shop gets, he wants to give one haircut every 15 minutes and never any more (otherwise, he might get burnt out you see). That is the throttling problem: how do you make sure events are processed (a haircut is given) no more than x number of times in a given time period?

My solution: keep a work queue, and have a scheduled executor pull work off the queue at a specified interval. Java 5 gives you all the tools to do this without resorting to busy waiting, polling, or writing scheduling code. The classes you need to know about are ArrayBlockingQueue and ScheduledThreadPoolExecutor.

ArrayBlockingQueue is a FIFO (First-In-First-Out) queue that supports blocking instead of busy waiting. When you take() an item from an ABQ, the call blocks until an item is available... no polling or sleeping to see if an item is ready to available. Just call take() and your code won't proceed until there is an element found.

The ScheduledThreadPoolExecutor supports executing both Runnable and Callable objects at a fixed interval. If you're looking to execute the same task every 1 second then STPE is what you need... Timer, for all intents and purposes, has been deprecated.

So here's the barber that just won't stand to be over-worked... setting it all up we need customers, a barber, and a waiting room:

class Customer {
String name
}

// waiting room can't hold more than 12!
def waitingRoom = new ArrayBlockingQueue(12)

def barber = Executors.newScheduledThreadPool(1)
barber.scheduleAtFixedRate({
println 'Barber: Next customer please!'
Customer customer = waitingRoom.take()
println "${customer.name} gets a haircut at ${new Date().format('H:m:s')}"
} as Runnable, 0, 15, TimeUnit.MINUTES)


Customer is a simple bean; nothing interesting here. The waiting room is an ArrayBlockingQueue filled with customers that need a haircut. And the barber is an executor service with a scheduled task to give haircuts. The number of threads in the scheduled thread pool is 1 because there's only one barber. The barber takes customers from the waiting room and cuts their hair once every 15 minutes. The call to waitingRoom.take() is blocking... if there is a customer ready then he is serviced immediately, and if one is not, then the call blocks until someone is available. Once thing to note... the waitingRoom has a size of 12... if a 13th customer is added then the calling code will either block until there is enough room or throw an exception. There is an API to do either case.

So how do customers get into the waiting room? That's where GPars actors come in. The barber shop is a "reactor" in GPars terminology. Messages can be sent to the barbershop ("Enter" the waiting room), and the reactor adds the customer to the waiting room. A maƮtre d' of sorts. Here it is in action:
def barberShop = new PooledActorGroup().reactor {message ->
switch (message) {
case Enter:
println "${message.customer.name} waits for a haircut..."
waitingRoom.add(message.customer)
break
}
}

class Enter {
Customer customer
}

barberShop << new Enter(customer: new Customer(name: 'Jerry'))
barberShop << new Enter(customer: new Customer(name: 'Phil'))
barberShop << new Enter(customer: new Customer(name: 'Bob'))
barberShop << new Enter(customer: new Customer(name: 'Ron'))

The barberShop is a PooledActorGroup, a GPars object, and the "actor framework" just means adding a closure to the reactor() method of that group. The closure, or actor, and responds to Enter messages by adding the customer to the waitingRoom. At the bottom you see the nice << syntax for posting events to the ActorGroup.

So there you have it. There are many ways to do this, but I think the Java 5 Concurrency libraries are some of the best options. I'd be interested to hear other ideas too. Now go give those hippies some haircuts!

Groovy Shell gets some Color

Well, well, it looks like Groovy Shell (groovysh) is starting to catch up to the other IDEs. Yesterday, support for colored output was added!

The Jansi library has added to the Groovy 1.8 snapshot, and now you get color coded output on all platforms, including Windows. Here is an Ubuntu screenshot:

And here's how to make it work in 3 easy steps:

1) Download Jansi and put it in your classpath
2) Get the nightly Groovy install*
3) Invoke groovysh with the -C parameter!

* As an alternative, it is incredibly simple to build Groovy from source:

svn co https://svn.codehaus.org/groovy/trunk/groovy/groovy-core
ant install -DskipTests=true
Happy Evaluating!

Thursday, December 10, 2009

Groovy 2009 Year in Review and 2010 Predictions

Groovy in 2009

Groovy 1.6 Released
Groovy 1.6 was released at the beginning of the year, and the most exciting new features have turned out to be Grape and AST Transformations.

Grape allows a developer to declare dependencies within their Groovy source code and then, at runtime, Groovy will download and install the dependencies using Ivy repositories. Want to ship scripts to your operations team? You no longer need to email or build JARs! It's no Jigsaw, but maybe that's a good thing.

AST Transformations allow developers to hook into the Groovy compiler and alter the way the code is compiled. This has enabled great work like the @Bindable and @Delegate annotations, as well as many forward thinking (read: visionary) libraries like the Spock testing framework and the CodeNarc static code analysis tools. Watch for more cool libraries and frameworks to use these features in 2010.

Griffon Released
While Flex and JavaFX duked it out for developer mindshare in the coveted (and hyped) RIA space, a groovier team quietly forked the Grails codebase and adapted it for Swing desktop applications. Griffon is way more than a dynamically typed builder pattern on top of Swing components. Griffon gives you property binding to widgets (you're not the only one Flex), a standard and simple MVC architecture without a spaghetti monster diagram (that's you PureMVC), more components than just a TextBox (the complete JavaFX widget set last Winter), a plugin system that allows you to decompose problems into reusable addons, and an easy way to deploy your app via webstart. If the Griffon team can keep the energy they had in 2009 then 2010 should be the year of the lion. Or eagle... or dog. What the hell is a griffon anyway?

Groovy Tooling Explosion
Looks like IntelliJ IDEA has some competition for best Groovy IDE. The Groovy Eclipse plugin got new life as Andrew Eisenberg revived the project, and SpringSource released better Grails support in SpringSource Tool Suite. Was the open sourcing of IDEA a response to the new competition? Who cares, it's free now! While IDEA is still the best IDE for Groovy, Groovy users will surely benefit from each IDE maker trying to outdo the other.

VMWare Buys SpringSource
Seriously, who saw this coming? This week at Groovy/Grails Exchange, Graeme Rocher demoed deploying to the cloud from his IDE (according to Twitter). Easy cloud deployment is good news... it will end the monthly "who do you use for Java hosting?" questions on user groups. Now if only the price would come down.

GR8 Conference
A Groovy conference created by the community, for the community, and priced for the community. It's great to see not for profit additions to the Groovy conference scene, and next year sees two GR8 events: one in Europe and one in North America (Minneapolis!). In other community news, Chicago Groovy Users Group started posting video sessions to blip.tv. Can we get some other GUGs to do the same?

A Groovy 2010

Don't think of these as predictions... think of them more as premature facts.

Gradle

To be clear: Gradle is not a Groovy technology. It is an enterprise build system written in Java with Groovy used as a build script. Anyway, the 0.9 release will include "Smart Execution/Incremental Compile" and 1.0 will support multi-threaded builds. These are enterprise level features that would be totally unique to Gradle... and they're sure to intice a lot of unhappy Maven developers. If the Gradle team can hit 1.0 and publish a book(!), then a lot of people will migrate.

GPars
I can't find anyone with anything bad to say about either the Fork/Join Framework or BMW Motorcycles... and I just sold my bike to spend more time coding. GParallelizer hasn't been widely adopted to date, in my opinion because it chased the Actor-Model hype a little too strongly. But now it's been rebranded GPars and an all-star team has been assembled to work on it. This isn't a good project to just follow, it's a good project to download and play with. Get the bits and join the mailing list. Your opinion counts! It's too bad that they hate cool the logo I made for them.

Griffon
The decision by the Grails team to make almost everything a plugin was genius. It provides a standard mechanism for everyone to modularize their own applications, and provides an easy path for users to push their non-business-critical plugins back into the community. If Griffon users embrace the plugin system, and then push their plugins back to the community, then Griffon could be a real alternative to JavaFX/Flex by the end of the year.

Java Closures
I wish the JDK team the best of luck meeting their September 2010 release deadline. While I have doubts that JDK 7 will ship in 2010, I do believe the closure syntax will be decided upon. And Groovy will be the first Java language to support that syntax. Whether a version of Groovy containing Java closures actually ships before JDK 7 is probably dependent on how the Groovy team wants to address the modularization issues of Jigsaw, which sounds like a much harder problem to solve.

Groovy IDE Support Improves... a little
IntelliJ IDEA still leads in features by a wide margin, but Eclipse and STS aren't stealing IDEA users, they're stealing TextMate users. People just want to debug without parsing all the files in the world. IDEA will remain the sole provider of Groovy refactorings, intentions, and auto-completions. But Eclipse will finally become a better alternative than a text editor. However, the open sourceing of IDEA should make it easier (and faster) to get IDEA support for newer frameworks, which is a good thing.

Groovy-User Mailing List Shuts Down
For the entire month of June, all posts to groovy-user will be answered with the same response: "This is covered in Groovy in Action 2nd Edition". By the end of the month admins will simply replace the mailing list home page with an advertisement for the book.

What Won't Happen

InvokeDynamic
InvokeDynamic is set to greatly improve implementing and running dynamic languages on the JVM. Only it won't be released until September 2010 at the earliest. Sure you can get the OpenJDK now, but most users won't do that. I predict InvokeDynamic being the story of 2011, not 2010... and even then I bet the JRuby guys beat us to it.

The Java Store
Let me get this straight... you want me to pay US$50 yearly so that I can give my Griffon app away free on the Java Store? You gotta be kidding. Griffon + the Java Store could be a match made in heaven: Griffon makes JNLP Webstart simple to configure and the Java Store handles hosting the files. But Sun/Oracle is turning too many hobbiest and small time developers away with their entrance fee. Are you listening Mr Ellison? I said I want... oh wait, you're not listening. How hard would it be to make the Groovy Store?

This was fun. What are your Groovy 2009 highlights and 2010 predictions?

Thursday, December 3, 2009

Simple XML Testing from Java

2009 is coming to a close and I'm writing a blog post about Java and XML. The blog's called "behind the times" for a reason: no fancy dynamic languages, JSON, or REST. Straight up XML on Java action.

One of my favorite editions to our enterprise toolset this year was XMLUnit. We'd been using Groovy in testing, and multi-line strings led to a ton of expressiveness in test cases... but then we stopped using Groovy. I switched back to Java testing and was left with making String based assertions and doing String#contains() calls. Not ideal; enter XMLUnit.

XMLUnit supports XML based equality comparisons so that things like these two snippets are equal:

<root/>

<root></root>

As well as these:
<root>data</root>

<root>
data
</root>

In fact, there's a whole gaggle of options around what is a meaningful versus a meaningless difference. For instance, I often consider two dates equal as long as they are formatted correctly (ignoring those pesky timestamp issue is nice).

The problem with XMLUnit is that the API is not as nice for the simple case as it could be. What I want is a simple custom assertion that asserts two XML snippets as similar. Something like this:
XmlAssertions.assertXmlSimilar("<root/>", "<root></root>"); 
XmlAssertions.assertXmlSimilar("<root>data</root>", "<root>\ndata\n</root>\n");

This was as simple as creating a small utility class and hiding the XMLUnit API behind a nicer custom assertion:
import java.util.List;
import junit.framework.*;
import org.custommonkey.xmlunit.*;

public class XmlAssertions {

private static final String ERROR_MSG = "XML comparison failure. \nExpected: %s\nReceived: %s\n%s";

static {
XMLUnit.setIgnoreWhitespace(true);
}

public static void assertXmlSimilar(String expected, String actual) {
try {
Diff diff = new Diff(expected, actual);
List differences = new DetailedDiff(diff).getAllDifferences();
Assert.assertTrue(
String.format(ERROR_MSG, expected, actual, differences),
diff.similar());
} catch (Exception ex) {
Assert.fail(String.format(ERROR_MSG, expected, actual, ex.getMessage()));
}
}
}

The raw XMLUnit code is clearly not something you want to see within the body of a test method. The custom assertion seems simple, but it's made a real pleasure of writing XML based functional tests around all our web services. Feel free to steal my code here: http://svn.assembla.com/svn/SampleCode/xmlunit/XmlAssertions.java