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

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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!).

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

java ,lua

Published at DZone with permission of Stefan Reich. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}