Hello World!

With AsyncScala you need very little to dive in the world of even-driven programming. The HelloWorld is possible here as well.

import net.sf.asyncobjects.asyncscala._
import vats._
import AsyncControl._

/**
 * The simple hello world program
 */
object HelloWorld {
  def main(args: Array[String]) {
    def vat = Vat.current
    println("Hello, World! " + vat)
    val r = doAsync {
      println("Hello, World from the vat! " + vat)
      aLater {
        "A value from vat!"
      }
    }
    println("The result = " + r)
    println("Left context! " + vat)
  }
}

This program produces the following output:

Hello, World! null
Hello, World from the vat! net.sf.asyncobjects.asyncscala.vats.SingleThreadVat@1d8957f
The result = A value from vat!
Left context! null

There are the following things to note:

  • doAsync method from AsyncControl object starts the vat in the current thread and initiates asynchronous operation specified by its body. This method exits when operation specified in the body finishes.
  • "Vat.current" allows to see the vat that is currently associated with the current thread, as we see in the output, no vat is associated outside of doAsync. And there is a SingleThreadVat inside doAsync.
  • aLater is a special asynchronous operation that starts its body on the next turn. And this operation finishes when its body finishes with the same outcome.

The code is executed in the following sequence:

  1. A SingleThreadVat is created by doAsync (from AsyncControl) operation
  2. An event that starts body of doAsync is sent to the vat, so it would be dispatched later
  3. The vat is started on the current thread. This initiate event dispatch loop. So event, that was sent earlier is dispatched.
  4. When event is dispatched, it starts body, and starts listening to the promise returned by body.
  5. The body starts aLater operation, and as result of aLater operation returns a promise, this promise starts to be watched.
  6. On the next turn, the body or aLater operation is started (also from AsyncControl). A string value returned by it is immediately converted to an already resolved Promise that contain string.
  7. aLater operation subscribes to the Promise). and immediately detects that it promise is already resolved, so aLater operation has been finished. It now uses resolver to notify everyone who has been waiting for its termination.
  8. doAsync operation receives notification that promise returned from its body is resolved. So now it is time to stop the event dispatch loop, and return result to the creator. Vat is stopped, and the current thread is no more associated with a vat

In the next section these elements will be discussed in much greater details.