Friday, July 2, 2010

Value types in java

Value types are crucial feature overlooked by the jvm and the java language.

With value types writing high performance, low allocation, cache friendly code is much easier.

For instance: in a physics application you cannot allocate Vector3d on the heap every time you need one. In java, to prevent 1.000.000 allocations per second one has to write convoluted code that reuses vectors every time. With value types this is not necessary, the new keyword does not allocate value types on the heap but on the method stack.

And don't believe when someone says that the JIT will optimize this for you, it is just not true. There are several dataflow patterns that the JIT cannot follow to optimize. Also immutable classes do not fully solve the problem (if you trust that the JIT will understand them), they just create more problems for the programmer.
An immutable Matrix4d is more expensive to update than a mutable one.

I've come across this problem writing game code (physics and rendering) in java.

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.