Functions are to be composed. In fact, composing side-effect-free functions is very easy. Much easier and reliable than composing objects, for example.
Given the same input, functions always return the same result, they never change their behavior unexpectedly nor they break when multiple threads call them at the same time.
h3. Functions in Groovy
We can treat Groovy closures as functions. They take arguments, do their calculation and return a value. Provided you don't let your
closures touch anything outside their scope, your closures are well-behaved pure functions. Functions that you can combine for a better good.
{code}
def sum = (0..100000).inject(0, {a, b -> a + b})
{code}
For example, by combining a function adding two numbers with the _inject_ function, which iterates through the whole collection,
you can quickly summarize all items. Then, replacing the _adding_ function with a _comparison_ function will immediately give you a combined function calculating maximum.
{code}
def max = myNumbers.inject(0, {a, b -> a>b?a:b})
{code}

You see, functional programming is popular for a reason.

h3. Are we concurrent yet?
This all works just fine until you realize you're not utilizing the full power of your expensive hardware. The functions are plain sequential.
No parallelism in here. All but one processor core do nothing, they're idle, totally wasted.
{note}
Those paying attention would suggest to use the _Parallel Collection_ techniques described earlier and they would certainly be correct.
For our scenario described here, where we process a collection, using those _parallel_ methods would be the best choice.
However, we're now looking for a *generic way to create and combine asynchronous functions* , which would help us
not only for collection processing but mostly in other more generic cases, like the one right below.
{note}
To make things more obvious, here's an example of combining four functions, which are supposed to check whether a particular web page matches the contents of a local file.
We need to download the page, load the file, calculate hashes of both and finally compare the resulting numbers.
{code}
Closure download = {String url ->
    url.toURL().text
}

Closure loadFile = {String fileName ->
    ...  //load the file here
}

Closure hash = {s -> s.hashCode()}

Closure compare = {int first, int second ->
    first == second
}

def result = compare(hash(download('http://www.gpars.org')), hash(loadFile('/coolStuff/gpars/website/index.html')))
println "The result of comparison: " + result
{code}
We need to download the page, load up the file, calculate hashes of both and finally compare the resulting numbers.
Each of the functions is responsible for one particular job. One downloads the content, second loads the file, third calculates the hashes
and finally the fourth one will do the comparison. Combining the functions is as simple as nesting their calls.

h3. Making it all asynchronous

The downside of our code is that we don't leverage the independence of the _download()_ and the _loadFile()_ functions.
Neither we allow the two hashes to be run concurrently. They could well run in parallel, but our way to combine functions restricts any parallelism.

Obviously not all of the functions can run concurrently. Some functions depend on results of others. They cannot start before the other function finishes.
We need to block them till their parameters are available. The _hash()_ functions needs a string to work on. The _compare()_ function needs two numbers to compare.

So we can only parallelize some functions, while blocking parallelism of others. Seems like a challenging task.

h3. Things are bright in the functional world

Luckily, the dependencies between functions are already expressed implicitly in the code. There's no need for us to duplicate the dependency information.
If one functions takes parameters and the parameters need first to be calculated by another function, we implicitly have a dependency here. The _hash()_ function
depends on the _loadFile()_ as well as on the _download()_ functions in our example.
The _inject_ function in our earlier example depends on the results of the _addition_ functions invoked gradually on all the elements of the collection.

{note}
However difficult it may seem at first, our task is in fact very simple. We only need to teach our functions to return _promises_ of their future results. And we need to teach the other functions
to accept those _promises_ as parameters so that they wait for the real values before they start their work.
And if we convince the functions to release the threads they hold while waiting for the values, we get directly to where the magic can happen.
{note}

In the good tradition of _GPars_ we've made it very straightforward for you to convince any function to believe in other functions' promises. Call the _asyncFun()_ function on a closure
and you're asynchronous.
{code}
withPool {
    def maxPromise = numbers.inject(0, {a, b -> a>b?a:b}.asyncFun())
    println "Look Ma, I can talk to the user while the math is being done for me!"
    println maxPromise.get()
}
{code}

The _inject_ function doesn't really care what objects are being returned from the _addition_ function, maybe it is just a little surprised that
each call to the _addition_ function returns so fast, but doesn't moan much, keeps iterating and finally returns the overall result to you.

Now, this is the time you should stand behind what you say and do what you want others to do. Don't frown at the result and just accepts that you got back just a promise.
A *promise* to get the result delivered as soon as the calculation is done. The extra heat coming out of your laptop is an indication the calculation
exploits natural parallelism in your functions and makes its best effort to deliver the result to you quickly.

{note}
The _promise_ is a good old _DataflowVariable_ , so you may query its status, register notification hooks or make it an input to a Dataflow algorithm.
{note}

{code}
withPool {
    def sumPromise = (0..100000).inject(0, {a, b -> a + b}.asyncFun())
    println "Are we done yet? " + sumPromise.bound
    sumPromise.whenBound {sum -> println sum}
}
{code}

{note}
The _get()_ method has also a variant with a timeout parameter, if you want to avoid the risk of waiting indefinitely.
{note}

h3. Can things go wrong?

Sure. But you'll get an exception thrown from the result promise _get()_ method.

{code}
try {
    sumPromise.get()
} catch (MyCalculationException e) {
    println "Guess, things are not ideal today."
}
{code}

h3. This is all fine, but what functions can be really combined?

There are no limits. Take any sequential functions you need to combine and you should be able to combine their asynchronous variants as well.

Back to our initial example comparing content of a file with a web page, we simply make all the functions asynchronous by calling
the _asyncFun()_ method on them and we are ready to set off.

{code}
    Closure download = {String url ->
        url.toURL().text
    }.asyncFun()

    Closure loadFile = {String fileName ->
        ...  //load the file here
    }.asyncFun()

    Closure hash = {s -> s.hashCode()}.asyncFun()

    Closure compare = {int first, int second ->
        first == second
    }.asyncFun()

    def result = compare(hash(download('http://www.gpars.org')), hash(loadFile('/coolStuff/gpars/website/index.html')))
    println 'Allowed to do something else now'
    println "The result of comparison: " + result.get()
{code}

h3. Calling asynchronous functions from within asynchronous functions

Another very valuable characteristics of asynchronous functions is that their result promises can also be composed.

{code}
import static groovyx.gpars.GParsPool.withPool

  withPool {
      Closure plus = {Integer a, Integer b ->
          sleep 3000
          println 'Adding numbers'
          a + b
      }.asyncFun()

      Closure multiply = {Integer a, Integer b ->
          sleep 2000
          a * b
      }.asyncFun()

      Closure measureTime = {->
          sleep 3000
          4
      }.asyncFun()

      Closure distance = {Integer initialDistance, Integer velocity, Integer time ->
          plus(initialDistance, multiply(velocity, time))
      }.asyncFun()

      Closure chattyDistance = {Integer initialDistance, Integer velocity, Integer time ->
          println 'All parameters are now ready - starting'
          println 'About to call another asynchronous function'
          def innerResultPromise = plus(initialDistance, multiply(velocity, time))
          println 'Returning the promise for the inner calculation as my own result'
          return innerResultPromise
      }.asyncFun()

      println "Distance = " + distance(100, 20, measureTime()).get() + ' m'
      println "ChattyDistance = " + chattyDistance(100, 20, measureTime()).get() + ' m'
  }
{code}

If an asynchronous function (e.f. the _distance_ function in the example) in its body calls another asynchronous function
(e.g. _plus_ ) and returns the the promise of the invoked function, the inner function's ( _plus_ ) result promise will compose with the outer function's ( _distance_ )
result promise. The inner function ( _plus_ ) will now bind its result to the outer function's ( _distance_ ) promise, once the inner function (plus) finishes its calculation.
This ability of promises to compose allows functions to cease their calculation without blocking a thread not only when waiting for parameters,
but also whenever they call another asynchronous function anywhere in their body.

h3. Methods as asynchronous functions

Methods can be referred to as closures using the _.&_ operator. These closures can then be transformed using _asyncFun_ into composable asynchronous functions just like ordinary closures.

{code}
class DownloadHelper {
    String download(String url) {
        url.toURL().text
    }

    int scanFor(String word, String text) {
        text.findAll(word).size()
    }

    String lower(s) {
        s.toLowerCase()
    }
}
//now we'll make the methods asynchronous
withPool {
    final DownloadHelper d = new DownloadHelper()
    Closure download = d.&download.asyncFun()
    Closure scanFor = d.&scanFor.asyncFun()
    Closure lower = d.&lower.asyncFun()

    //asynchronous processing
    def result = scanFor('groovy', lower(download('http://www.infoq.com')))
    println 'Allowed to do something else now'
    println result.get()
}
{code}

h3. Using annotation to create asynchronous functions

Instead of calling the _asyncFun()_ function, the _@AsyncFun_ annotation can be used to annotate Closure-typed fields.
The fields have to be initialized in-place and the containing class needs to be instantiated withing a _withPool_ block.

{code}
import static groovyx.gpars.GParsPool.withPool
import groovyx.gpars.AsyncFun

class DownloadingSearch {
    @AsyncFun Closure download = {String url ->
        url.toURL().text
    }

    @AsyncFun Closure scanFor = {String word, String text ->
        text.findAll(word).size()
    }

    @AsyncFun Closure lower = {s -> s.toLowerCase()}

    void scan() {
        def result = scanFor('groovy', lower(download('http://www.infoq.com')))  //synchronous processing
        println 'Allowed to do something else now'
        println result.get()
    }
}

withPool {
    new DownloadingSearch().scan()
}
{code}

h4. Alternative pools

The _AsyncFun_ annotation by default uses an instance of _GParsPool_ from the wrapping withPool block. You may, however, specify the type of pool explicitly:
{code}
@AsyncFun(GParsExecutorsPoolUtil) def sum6 = {a, b -> a + b }
{code}

h4. Blocking functions through annotations

The _AsyncFun_ also allows the user to specify, whether the resulting function should have blocking (true) or non-blocking (false - default) semantics.

{code}
@AsyncFun(blocking = true)
def sum = {a, b -> a + b }
{code}

h4. Explicit and delayed pool assignment

When using the _GPars(Executors)PoolUtil.asyncFun()_ function directly to create an asynchronous function you have two additional options
to assign a thread pool to the function.

# The thread pool to use by the function can be specified explicitly as an additional argument at creation time
# The implicit thread pool can be obtained from the surrounding scope at invocation rather at creation time

When specifying the thread pool explicitly, the call doesn't need to be wrapped in an _withPool()_ block:
{code}
Closure sPlus = {Integer a, Integer b ->
    a + b
}

Closure sMultiply = {Integer a, Integer b ->
    sleep 2000
    a * b
}

println "Synchronous result: " + sMultiply(sPlus(10, 30), 100)

final pool = new FJPool()

Closure aPlus = GParsPoolUtil.asyncFun(sPlus, pool)
Closure aMultiply = GParsPoolUtil.asyncFun(sMultiply, pool)

def result = aMultiply(aPlus(10, 30), 100)

println "Time to do something else while the calculation is running"
println "Asynchronous result: " + result.get()
{code}

With delayed pool assignment only the function invocation must be surrounded with a _withPool()_ block:

{code}
Closure aPlus = GParsPoolUtil.asyncFun(sPlus)
Closure aMultiply = GParsPoolUtil.asyncFun(sMultiply)

withPool {
    def result = aMultiply(aPlus(10, 30), 100)

    println "Time to do something else while the calculation is running"
    println "Asynchronous result: " + result.get()
}
{code}

On our side this is a very interesting domain to explore, so any comments, questions or suggestions on combining asynchronous functions or hints about its limits are welcome.
