Playing with Structured concurrency in Kotlin

Photo by Jeff Prieb from FreeImages

Studying about Kotlin Coroutine, I often read Structure concurrency but what it really means? Structured how many times do you hear this word about programming? Structured programming, is a programming paradigm born to improve code quality and clarity, by using structured control flow constructs of selection (if…then…elen) and repetition (while and for), block structures and subroutines. This concept born by some considerations made by Edsger W. Dijkstra in “Go To Statement Considered Harmful”.

Basically we have to stop to write:

In favor of:

Because rely on a row index makes our software very hard to maintain, while programming using block structures and subroutine is very helpful when we need to modify our code.

Why we cannot do the same when we have to do concurrency programming? Martin Sústrik, the ZeroMQ creator, introduce this concept for the first time in his blog, Roman Elizarov like his ideology and introduce this concept in Kotlin Coroutine two years later. Go back to our example…

Let’s imagine a simple game where the winner is who plays more times in 500 milliseconds:

As you can see in the console above the player continue playing because the interruption of parent thread doesn’t stop the children execution. Of course, we can fix it, but this isn’t so easy and the code will not so clear to understand. Thanks to Kotlin syntax our code is structured, thread { … } seems a syntactic construct, but it isn’t actually structured concurrency because the lifetime of a thread isn’t bound to a code block. So, we are violating concepts behind structured programming.

So let’s go with a refactoring using coroutine:

Now the players stop to play when the game ends!

So we reach our target about structured concurrency because using the launch syntactic construct the lifetime of a thread is bound to a code block and our code readability is awesome :)

This isn’t enough, another interesting feature of Structured concurrency is that the parent thread will complete only when all children complete.

In the example above the parent launch construct will print “Complete! — main” only after the completion of all children tasks.

We can do that in plain Java? Not yet, but Fiber is coming:

Do you wish to learn more? Visit this forum to find a lot of useful resources and discussion about Structured concurrency:

More on Kotlin Coroutine

Further reading

Open-space invader, bug hunter and software writer