18.5. Asynchronous programming helpers (gololang.Async)

This module offers asynchronous programming helpers, especially execution context agnostic promises and futures. The provided APIs are orthogonal to the execution strategy: it is up to you to execute code from the same thread, from a separate thread, or by pushing new tasks to a service executor.

Here is an example:

module samples.Concurrency

import java.util.concurrent
import gololang.Async

local function fib = |n| {
  if n <= 1 {
    return n
  } else {
    return fib(n - 1) + fib(n - 2)
  }
}

function main = |args| {
  let executor = Executors.newFixedThreadPool(2)
  let results = [30, 34, 35, 38, 39, 40, 41, 42]:
    map(|n| -> executor: enqueue(-> fib(n)):
      map(|res| -> [n, res]))
  reduce(results, "", |acc, next| -> acc + next: get(0) + " -> " + next: get(1) + "\n"):
    onSet(|s| -> println("Results:\n" + s)):
    onFail(|e| -> e: printStackTrace())
  executor: shutdown()
  executor: awaitTermination(120_L, TimeUnit.SECONDS())
}

This example takes advantages of an executor augmentation and composable promises and futures to compute Fibonacci numbers.