Tuesday, October 23, 2007

Java Threads

Unfortunately, one of the (few :) ) drawbacks of Java applets is that in order to have a consistent game loop, you need to run the main game code in another thread. (I may be wrong here; please let me know if I am). I've blogged before about why threads in any language are a pain as they exponentially complicate a program, not least because variables can change mid-line.

Another problem that I always forget, is that in Java, threads don't access another threads data directly (unless you use the volatile keyword). Forgetting this caused me several hours of frustration and I even wrote my own ArrayList class to try and fix it. Basically, the code in my thread's run() function was accessing the class-level arraylist. But completely failing to affect it! It was calling "arraylist.remove(13)" (say), but after it had run, that object still existed in the list! What was going wrong?!?

Well, I've already said the answer. It was accessing a copy of the arraylist, not the list itself. As soon as I discovered and fixed this, all was well and I could go back to enjoying writing applets again.

1 comment:

Anonymous said...

Concurrency and JAVA is like programming object oriented in ASM.

It's possible, but it is a bad idea. Java does not support concurrency. Not in a way, that keeps your code maintainable, that can give you garantuees about progress, etc.

If you want nice concurrency, go with Haskell, Clean, Erlang, Oz, etc. Unfortunately, there are no fast object-oriented programming languages with declarative semantics. There really is a need for it though.

Have you read Tim Sweeney's article about what's the perfect game programming language would be? (he is lead developer of the Unreal Engine).

PDF Link: