Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.


You may have to adjust your file for messages at log level FINEST to be displayed.

Asynchronous Decorators using GPars

Using the example code in Panini for inspiration. Here is a Groovy version that avoids using an @AddedBehavior annotation at the expense of not having as general an algorithm for selecting the methods to decorate. This isn't a limitation of the particular approach chosen but just a simplification for illustrative purposes (but don't assume below is an exact equivalent).

Code Block

import static groovyx.gpars.GParsPool.withPool

interface Document {
    void print()
    String getText()

class DocumentImpl implements Document {
    def document
    void print() { println document }
    String getText() { document }

def words(String text) {
    text.replaceAll(/[^a-zA-Z]/, ' ').trim().split(/\s+/)*.toLowerCase()

def avgWordLength = {
    def words = words(it.text)
    sprintf "Avg Word Length: %4.2f", words*.size().sum() / words.size()
def modeWord = {
    def wordGroups = words(it.text).groupBy {it}.collectEntries{ k, v -> [k, v.size()] }
    def maxSize = wordGroups*.value.max()
    def maxWords = wordGroups.findAll{ it.value == maxSize }
    "Mode Word(s): ${maxWords*.key.join(', ')} ($maxSize occurrences)"
def wordCount = { d -> "Word Count: " + words(d.text).size() }

def asyncDecorator(Document d, Closure c) {
    ProxyGenerator.INSTANCE.instantiateDelegate([print: {
        withPool {
            def result = c.callAsync(d)
            println result.get()
    }], [Document], d)

Document d = asyncDecorator(asyncDecorator(asyncDecorator(
        new DocumentImpl(document:"This is the file with the words in it\n\t\nDo you see the words?\n"),
//        new DocumentImpl(document: new File('AsyncDecorator.groovy').text),
        wordCount), modeWord), avgWordLength)