I'm currently learning for an exam. In an multiple choice question of an old exam are two different versions of a for loop marked as valid:
finish async for (i in array) async {
...
}
and
finish for (i in array) async {
...
}
What is the difference of those two versions?
async Statement
Spawns a new activity executing the Statement.
In your second version is one activity spawned per loop execution. If n is the size of your array you will spawn n activities. In your first version you also spawn an extra activity for the loop itself: You spawn n + 1 activities. You can write it also as: (which may be more clear for you)
finish async {
for (i in array) {
async {
...
}
}
}
Actually i don't have a source other than the language specification, but you can test the behaviour as it computes as expected. If you remove the first async no activity for the loop is created and "hello from starter" is printed after "hello from loop". With the extra async "hello from starter" will be printed first:
public static def main(Rail[String]) {
finish {
async { //to be removed
for (i in [1,2,3]) {
async {
Console.OUT.println("Hello from executing activity " + i + "!");
}
}
System.sleep(3000l); //wait 3s
Console.OUT.println("Hello from loop!");
}
Console.OUT.println("Hello from Starter!");
}
}