The Artima Developer Community
Sponsored Link

Artima Developer Spotlight Forum
Asynchronous Methods in Groovy

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Frank Sommers

Posts: 2642
Nickname: fsommers
Registered: Jan, 2002

Asynchronous Methods in Groovy Posted: Jan 22, 2009 2:14 PM
Reply to this message Reply
Advertisement

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?

Topic: Becoming a Grass Farmer Previous Topic   Next Topic Topic: Entity Modeling and Object-Relational Mapping

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use