Over a million developers have joined DZone.

Java Can Have Coroutines!

DZone's Guide to

Java Can Have Coroutines!

A quick code snippet on how to create working coroutines in Java using JavaX.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Java can have coroutines like Lua has. Impossible? Not so! It can be done in JavaX (a Java dialect that compiles into Java source code).

For now, turning a function into a coroutine requires a bit of (straight-forward) source code transformation — but of course those transformations could later be automated too.

We can make working coroutines right now if we do the translation manually. [Working example!]

Example: A for loop

for (int i = 1; i <= 3; i++)
  print("Counting to " + i + "!");

Turns into this coroutine making expression:

_for(r { i = 1 }, func { i <= 3 }, r { i++ }, r {
  print("Counting to " + i + "!");

It basically has a few more brackets; and you need to put the i variable in a suitable place (static or in an object, not local).

Then, voila: Your code can be run as a coroutine, which means, it can be run in small steps (via the doStep function) and interrupted at any time, thereby yielding time to other coroutines. A useful feature indeed, for example to parallelize multiple computations on a single processor.

You see: The impossible becomes possible with JavaX!

Next time, if you ask me to, we can cover how to use function calls in coroutines (including recursion!).

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

java ,lua

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}