How to write a toy JVM
zserge.com
zserge.com
- https://github.com/lihaoyi/Metascala
Interpreting code in Metascala is about 100x slower than just running it, and interpreting code in Metascala interpreted by Metascala is about 10,000x slower than just running it. Not going to win any performance benchmarks, but it's a cool demonstration of how a JVM works.
All the runtime data structures, memory allocation and garbage collection, method dispatch logic, stack trace management, exceptions, inheritance, object layouts, etc. are all implemented in a relatively small amount of relatively simple code.
For example, here is the implementation of the heap, which allocates the VM's objects inside a big byte array and has a simple copying semispace garbage collector to clean them up:
- https://github.com/lihaoyi/Metascala/blob/master/src/main/sc...
It's JVMs all the way down
Back at uni, I've done this with the ZMachine [1], in (non-idiomatic, newbie) Haskell [2], using Zork 1 as the blob. Sixteen years after, I remember the elation when my interpreter first printed out the familiar message:
You are standing in an open field west of a white house, with a boarded front door.
My implementation was poor even by novice standards, i knew there was a lot of spaghetti but I didn't mind. Implementing each opcode was like beating a level in a video game - and it worked, not perfectly and with some unsolved bugs. Tetris worked flawlessly though.
"Whether we like it or not, but Java is one of the most widely used programming languages. However, since most of the applications in Java are either too boring or too complex - not every Java developer has enough curiosity to look under the hood and see how JVM works."
I don't think the author contradicted what you just said. I guess you may be confused by the "whether we like it or not" part? I feel like the author is commenting on Java the language (vs the JVM).
I don't think it's ever been much actual use to me in programming, but was nice-to-have background knowledge.
I'm very tempted to pick a hard copy up!
I've come to TinyVM [1] made for some Lego system which uses about 10kB of RAM. I was wondering about porting it to other micro-controllers...
edit, found it : https://dzone.com/articles/the-magic-word-in-java-cafebabe
Now I feel that there should be a website that lists all kinds of fun hex words.
Like CAFEFACE
grep -i '^[0-9a-f]*$' /usr/share/dict/words
0 - o
1 - I
3 - E (redundant)
4 - A (redundant)
5 - S
6 - G
7 - T
There's also DEFEC8ED ("defecated"), which was used by OpenSolaris for core dumps.
(Plus, didn't "if err != nil" give it away?)
http://www.catb.org/jargon/html/N/nasal-demons.html
In there is a link to the thread that originated the term from 1992:
http://groups.google.com/groups?hl=en&selm=10195%40ksr.com
If you scroll to the bottom you’ll find possibly the most lost soul on the Internet reviving the most dead thread ever.
Occasionally there are such talks at Java ONE (now Code ONE), Voxxed, NDC.
JVM Languages Summit also has such talks.
http://openjdk.java.net/projects/mlvm/jvmlangsummit/
Talks from Cliff Click or Gil Tene.
Then you can have a look at implementations like JikesRVM (one of the first ones implemented in Java), OpenJ9 (open source variant of IBM's J9).
https://www.eclipse.org/openj9/
There is plenty of other stuff, but maybe this allows you to get going.
They compile the bytecode just-in-time to native machine code, using many of the same techniques a conventional native code compiler.
From the Hotspot Wikipedia page:
"Both VMs compile only often-run methods, using a configurable invocation-count threshold to decide which methods to compile."[1]
Also see very old discussions at StackOverflow[2][3]. Then of course there are compilers (eg. gcj) which compile to native up-front.
[1] https://en.wikipedia.org/wiki/HotSpot#Features
[2] https://stackoverflow.com/questions/7100365/why-doesnt-javas...
[3] https://stackoverflow.com/questions/16568253/difference-betw...
Who are you disagreeing with? I didn’t say that’s the only way they execute bytecode, did I?
The question was how it’s executed ‘after they warm up’.
> Then of course there are compilers (eg. gcj) which compile to native up-front.
But I was replying to someone who asked specifically about how ‘production JVMs’ do it, not how discontinued compilers do it.
Nope, my bad. Thanks for clarifying.
This is by design, and if you need everything compiled right away you can set the compilation threshold to 1.
I don't see any value in compiling parts of code that only gets executed during bootstrap.
Not disagreeing with you there, since stopping to compile code/optimize at runtime contributes to sluggish interactive performance.
No JVM I am aware of stops to compile - the compiler runs on a background thread while the application continues to run as normal.
https://www.oracle.com/java/technologies/javase/vmoptions-js...
Also bytecode verifier
> * Conversions (int to short, int to float, …).
float to string should be the most trivial of all
But we have to agree that JVM feels like steam engine running in the age of electric motors. With virtualisation available cheaply in every level (hardware, arch, OS and docker) virtualisation at runtime feels like overhead.
JVM was originally created for purpose of 'write once, run anywhere', which I think can be addressed in alternative ways, look at golang
These seem to be solving fundamentally different problems. Where do you see the overlap that might be able to be moved out of the jvm?
All of this has been possible for decades (eg cross compile C++), but Go is the first mainstream compiled-to-native language that I know that makes it easy. Thanks to this, I can run many utilities written in Go on my Windows box, written mostly by people who likely never even tested in on Windows. That's pretty amazing to me.
People just drop a Windows binary on GitHub and think "I'll get the PR if stuff doesn't work". They'd never do that if it cost them effort to cross build a Windows binary. People didn't do that before Go, and many modern OSS command line utilities / server apps only worked on unixes.
> and many modern OSS command line utilities / server apps only worked on unixes
This, I think, likely has more to do with being POSIX compatible and/or oriented for headless server usage where a shell is "home" for many 'nix admins.
The developer no longer cares what architecture the program will run on, it just works.
You compile to bytecode, and stop caring. The JVM becomes your only target architecture, regardless of what actual architecture the system has.
That's unlike C or pretty much any (all?) other compiled languages around in the early 90's when Java was still Oak and Gosling was just getting started.
But there's plenty use cases for which the go standard library offers a sufficiently good abstraction that cross compiling just works. The same holds for JVM apps for ages (and for nodejs etc etc) but not eg for C(++).
As a windows dev I very much noticed an increase in good CLI tools that just work on my box since Go got to the scene. I think that's cool.
With Java, you compile one “binary” and it works not just on three OSes, but all of them that have a JVM available. The beauty of it is that it’s as portable as an interpreted language, no cross-compilation needed at all.
From https://golang.org/doc/faq they say:
> Go does have an extensive library, called the runtime, that is part of every Go program. The runtime library implements garbage collection, concurrency, stack management, and other critical features of the Go language
I think people can argue all they want about semantics, what is a virtual machine? There are not "proper definition" for this. Ultimately, if you abstract away the details of the running environment, to me, you've created a virtual machine.
The Go FAQ continues by insinuating it isn't a virtual machine because it doesn't do just in time compilation and only ahead of time. I think that's just word play.
From https://en.m.wikipedia.org/wiki/Virtual_machine says:
> A process VM, sometimes called an application virtual machine, or Managed Runtime Environment (MRE), runs as a normal application inside a host OS and supports a single process. It is created when that process is started and destroyed when it exits. Its purpose is to provide a platform-independent programming environment that abstracts away details of the underlying hardware or operating system and allows a program to execute in the same way on any platform.
Personally, I think "Managed Runtime Environment" is a better term, and Go would definitely fall into that term.
So I recognize the difference are real. Just in time Vs ahead of time. But it isn't docker, or any other layer of virtualization which magically allow Go to run over many machines. Its because it has an extensive runtime that abstracts away their details. And this runtime has to be bundled in every compiled application. Maybe we should start talking about virtual runtimes?
So then are operating systems also virtual machines? Is the C standard library a virtual machine? This seems like a pointless definition to me.
> Maybe we should start talking about virtual runtimes?
Isn't that just called a runtime? Java is "virtual" because the instructions in the Java class files don't run directly on the CPU, unlike Go where the instructions in the binary do run directly on the CPU.
Kind of, the ISO C is defined in terms of the C abstract machine.
> The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.
https://www.cl.cam.ac.uk/teaching/1415/CandC++/lecture10.pdf
https://phoenix.labs.vu.nl/sysprog/cabs.pdf
And not all C implementations AOT compile to native code.
Here it seems specifically like OP wanted to say that they find ahead of time statically linked with cross compilation to be a more convenient model of code compilation and distribution.
With that in mind, we're now better equipped to compare and contrast, and discus the pros/cons.
When we restricted ourselves to VM vs non-VM, I didn't feel like we were in this meaningful zone.
And from that angle for example, we can see that Java offers ahead of time compilation, which can be statically linked as well if one wants too. One example is GraalVM native image. There were also some options before GraalVM that I think were all commercial. That said, I've yet to see a cross-compilation offering.
The JIT approach has benefits as well, the user doesn't need to select the appropriate package for their OS. The runtime distribution is shared between all apps that uses it. It's easier to offer debugging/profiling/measuring capabilities of the running application. The user can tweak certain parameters of the runtime or even choose an alternative runtime implementation. If runtime has any known security vulnerability, the user can upgrade it to a new secure version, without waiting for a new update of the app. Better peek performance of hot code paths can in theory be achieved. Just to name a few.
Another difference is Go has no intermediate representation. While Rust, C# and Java for example do. This intermediate representation is quite useful in allowing multiple languages to reuse the Java bytecode runtime. That's not as simple in Go, since Go is a harder target for compilation.
Etc.
Yes, there is a cost in footprint and warmup, but footprint is very often (though not always) the right cost. Of all software resources -- development, maintenance, memory, processing and bandwidth -- it's the cheapest (well, second to storage). By comparison Go is less RAM hungry but it's sluggish and opaque.
But the opinion that Go is sluggish and opaque is purely subjective. For anything but long running server apps, Java's memory consumption makes it feel sluggish, especially on desktop.
Also, when are the value types coming?
It is not. It's significantly slower than Java and has maybe 5% of its observability tools. Go is technologically more than a decade behind Java in compilation, GC, and observability. I'm not saying it's not good enough for certain things -- sometimes primitive and simple gets the job done, and you might not need a Ferrari to go to the grocery store -- but let's not turn an acceptable compromise into a win.
> Java's memory consumption makes it feel sluggish
Why? If you don't mind it performing as poorly as Go, you can reduce the heap size and pick a low-latency collector like ZGC, but really Java says, give me the cheapest resource, RAM, and in return you'll get something much better.
> especially on desktop
Java desktop applications consume less RAM than Electron ones, and IntelliJ is more snappy than Atom (and recently, unfortunately, vscode, too), although there are perfectly valid reasons to prefer Electron.
> Also, when are the value types coming?
I don't know. Not my area.
Edit: also I want to mention that Java was IMO the single one tech that saved the scene from being an Microsoft-only world, and also significantly paved the way for today's Linux dominance on the server-side; Java was picked by many devs because it helped to keep open the door for migrating to Solaris or Linux in an increasingly MS-dominated landscape in mid 90's
But you missed my point entirely. I did not call JVM a steam engine in derogatory way. On the contrary, steam engine is awesome piece of technology which had tremendous impact on industry.
But JVM has issues which recent runtimes have learnt and solved in different ways.
Such as?
Virtualisation is also not readily available from within userland. We're not at "each process runs in its own VM" yet. Perhaps we'd want "each browser tab runs in its own VM", which is kind of what Javascript aims to achieve.
Microsoft have also gone in this direction; they don't call the CLR a "VM" but it performs many of the same functions in order to run CIL/MSIL bytecode.