Ubergeek Question: Programming Java in ASM?

      • A pal of mine and I got to wondering about how multithreading is accomplished in Java, specifically how it is done on the machine code level. We cracked a few language/compiler writing books but couldn’t find any good explanations on the subject of multithreading. We both agreed we couldn’t see any way of achieving it without maintaining as many call stacks as threads, clocking process cycles during each thread -and- switching the different call stacks in and out when the threads are switched, something which sounds as if it would require an awful lot of overhead. Java is said by many to be too slow for 3D-game use, and if the above assumptions are true, it’s not hard to believe. Does a Java program with multiple threads maintain a separate stack for each thread or not? - MC

According to the book Core Java 2 Volume II Advanced Features

So on Unix for example it will use the pthread libraries. Context switching is expensive regardless of the language.

Heh, I thought this thread was going to be about assembling Java bytecode.

The virtual machine I’m currently working on works exactly as you described - each task has its own stacks. The priority level of each task is simply the number of instructions it gets to run per timeslice. I can’t think of any other way to do it, besides using OS threads and running multiple copies of the VM at once. But it’s not too bad… switching the stacks doesn’t involve much overhead, it’s done by simply changing a pointer.

Also, keep in mind that Java bytecode is typically compiled to native machine code these days (JIT), so it may be possible to hand all the thread control over to the OS.