Wednesday, June 16, 2010

jyield

Recently I created a project on google code, jyield.

jyield aims to provide java continuations support similar to c# yield coroutines.

The methods annotated with @Continuable become generators i.e. they can yield values and interrupt their processing until they are called again.

The following code show just that:

import jyield.Continuable;
import jyield.Yield;

public class Sample {

@Continuable
public static Iterable someNumbers() {
for(int i=0;i<5; i++) {
System.out.print(" #");
Yield.ret(i);
}
return Yield.done();
}

public static void main(String[] args) {
for (int i : someNumbers()) {
System.out.print(" "+ i);
}
}
}
// Output: #0 #1 #2 #3 #4


The foreach iterates over the iterator returned by the someNumbers method. Each time the iterator returns a value is actually a tiny bit of the someNumber being executed and interrupted.

This all happens on the stack of the calling method (main). It is done by changing the bytecode after the java compiler has created the .class.

I took the care of ensuring that try catch and synchronized blocks also behave well inside the continuable methods.

I intend to use this code in future game projects. Right now I am working on a game that uses C# and generators make my life much easier. Too bad java does not have then, ooops, now it has.

No comments:

Post a Comment