coroutine support

Lukas Stadler lukas.stadler at jku.at
Thu Nov 12 09:08:43 PST 2009


Hi everybody!

I've just checked in the first prototype of a coroutine implementation. 
It's implemented using the continuations framework, so it's not very 
speedy (~1µs per context switch in a simple example) but it allows me to 
experiment on how the API for coroutines could look like.
This is how it currently works:

public class CoroutineTest extends Coroutine {
    public CoroutineTest(CoroutineContext context) {
        super(context);
    }

    public static void main(String[] args) {
        CoroutineContext context = new CoroutineContext();
        new CoroutineTest(context);
        new CoroutineTest(context);
        context.start(null);
    }

    @Continuable
    protected Object run(Object value) {
        for (int i = 0; i < 10; i++) {
            System.out.println(i);
            yield(null);           
        }
        return null;
    }
}

The Coroutine class is very similar to the thread class, it can either 
be subclassed or provided with a CoRunnable object.
The main concept is that every coroutine is associated with a 
CoroutineContext when it is created. The coroutines will start to 
execute as soon as CoroutineContext.start is called and this method will 
not return unless all coroutines have finished. The coroutines are kept 
in a doubly-linked ring and the default scheduling (which can be changed 
by subclassing CoroutineContext) always just yields to the next 
coroutine in the ring.
The main drawback of using a coroutine context in this way is of course 
that coroutines are tied to a specific thread - is this a problem? A 
notion of "moving" a coroutine from one context (and thread) to another 
could be introduced, but a coroutine will always need to be associated 
with a context so that we can make sure it will end properly.
I'd be glad to hear what you guys think of this!

cheers
 Lukas


More information about the mlvm-dev mailing list