Asynchronous method calls allow a method to return immediately after invocation, and then optionally notify listeners when its execution completed. Such asynchronous invocations are important, for instance, in user interfaces, where the actual task of a method may take a long time to perform, and immediate return from the method can make the UI more responsive.
While Java or Groovy methods are synchronous by default, in a recent blog post, Asynchronous methods in Groovy, Václav Pech demonstrates how to add asynchronicity to Groovy method invocations. At the heart of Pech's technique is the ability to pass a closure to the method; that closure can then enable callbacks—or any other action upon completion of the method's real work:
Have you ever wanted to call a long-lasting method asynchronously? What is the simplest way to do so? Creating a new Thread and passing in a Runnable? Or building a thread pool and submit a Callable to it for processing? Well, if you're lucky enough to be using Groovy, all you need to do it to add an extra Closure parameter to your method call.
The most interesting aspect of this technique is that it takes advantage of Groovy's dynamic language features. If a method with the optional closure parameter is not found, such a method can be added dynamically to an object:
But wait, you may say, there's no such method called toUpperCase() taking a Closure for parameter on the String class, right? Sure, but that's why people love Groovy - we can add the method. And not only this one, but at the same time we'll enhance all methods on the String class to accept an extra Closure parameter. Under the covers these methods will call their original variants (without the Closure) in a newly created thread and pass the result of the computation into the Closure.
What do you think of Pech's description of adding asynchronous invocation to Groovy methods?