295 points · by yla92 · 3y ago · 178 comments
This breaks my brain thinking about it. A lot of what the JVM does is interpreting/JITing bytecode and ensuring it links/executes correctly, and writing that logic itself in Go is one thing. But how does Go's GC help you garbage collect objects in the JVM you're implementing?
For example, you have objects in the JVM heap, tracked by the code you're writing in Go. You need to do a GC run. How does the Go GC know about the objects you're managing in the JVM? Do you just... write wrapper objects in Go around each of them, and code up a destructor so that freeing the Go object frees the tracked JVM object? How do you inform the Go VM about which pointers exist to your JVM objects?
I realize I'm in way out of my depth here, and only have a "user"'s understanding of what GC's do, having never implemented one myself, but it seems crazy to me that Go's GC can Just Work with a VM you're writing in Go itself.
[1] For example https://pkg.go.dev/vuln/GO-2023-1704
Which tends to be cargo culted into "use these arguments when running java programs", thus a "hello world" responder gets allocated 128GB of ram.
Far from it, it is more natural to do that than anything else.
Simplified example:
type Array struct {
items *any[]
}
type Object struct {
fields map[string]*any
}
These are the JVM values, and when the references to them disappear, the JVM values they reference can be GC'd as well.syntax error: unexpected ], expected type argument list
and its also just poor style in general. "any" is already a pointer, so you would rarely design a pointer to any. example:
Naively, something like:
// Called when the hosted JVM code wants to allocate
func makeJVMObject() (jObj, error) {
var obj = new(jObj) // on go’s heap
// do stuff
return obj, nil
}
would make sense, except how do we keep track of who’s referencing it? JVM objects have fields which tell the GC how to crawl the object tree in the mark phase (and so do Go objects), but how do we make the Go GC aware of the fields the JVM knows about? A map maybe?Hmm, I guess a map could work… the jObj struct could have a map of fields it knows about, keys being the field name and values being where they point to…
Now that I think of it this probably must be how all GC’s work, they can’t rely on static information to know the fields of each type they’ve compiled, it’s gotta be something like a map somewhere.
I guess I may have answered my own question here.
In fact, I would go so far as to say that it's harder to implement those without Go's GC just working.
Sometimes you see add-on “conservative garbage collectors” that have to assume any word might be a pointer if it looks like an aligned address in an allocated page. They can’t move objects to do compaction because they’re never sure which words are not pointers.
Jacobin stores an object with a slice of its field values (each boxed as “any”) and types, so Go’s precise GC would be able to trace them: https://github.com/platypusguy/jacobin/blob/main/src/object/...
It's kind of cool actually.
I wonder if there's a future where somebody can just pick and choose language and runtime components parts to create the environment they want before even writing a line of code. We sort of do it a level lower with VMs and containers, and then pick and choose language features we want to use (e.g. C++), but I don't know of a good way to use Java's JVM, C#'s JIT, somebody else's memory profiler, another team's virtual memory subsystem etc. without writing a bunch of different pieces in different languages to get those benefits.
But we first want to get feature parity, before pivoting to performance. When we have feature parity, we'll run the Computer Language Benchmarks and post the results. That'll be fun to see!
Imho there is no way to do a fair comparison, as both implementations have completely different goals.
One thing that would be interesting is comparing the performance of some really simple command line program (e.g. `ls` or `cp` for small files) between Hotspot in interpreter mode, Jacobin and GraalVM native.
Jump tables for switch statements was only implemented last year. If you squint that's close to indirect threading, but still with at least one unnecessary conditional per op.
For the curious, here's their giant switch: https://github.com/platypusguy/jacobin/blob/c508ec50f55ef381... In practice compilers have always been finicky when it comes to coaxing them to emit jump tables from switch statements, and I bet this is especially truly for Go.
It has been a fun project to play around with for someone like me who thinks this kind of stuff is fun and interesting but will probably never get a chance to work on it full time. Cool to see it noticed, though!
[*] until the latter will implement condensers: https://openjdk.org/projects/leyden/notes/03-toward-condense...
The optimizations in JDK 9 are for reducing the file size of the JDK (in terms of number of classes) when distributed with a standalone application, but that by itself doesn’t significantly affect startup time I believe, because classes are lazy-loaded only as required in any case.
Faster start up time is in the works with projects like coordinated restore at checkpoint which will let you start a JVM up in an already "warmed" state.
Tangential, but a long time ago, I wanted to reuse a node.js slug library in .NET. I thought about trying to port it at first, but then I realized that this actual job didn't need to be terribly fast, so I instead embedded the Jurassic JS library into my code, and was able to load in the slug library that way directly). It wasn't especially fast (but actually faster than I thought it would be!), but it was certainly fast enough, and I didn't have to worry about not having feature parity.
(Saxon had since moved to transpiling the source code instead - the languages are close enough that this is fairly straightforward.)
The cool thing is that since this uses the Go garbage collector, you can create a very nice Go-native interface to that JVM code.
It seems the goals for this are purely academic and about figuring out how Java works. They'll probably just do a simple interpreter and not a JIT compiler. That would be good enough for a POC. Additionally, they already indicated that they'll use Go's garbage collector, which won't be setting speed records with this either. And Java's typical usage of memory might actually stress it out a bit. Then there is the standard library which is going to need plenty of support for things like Threads, IO, various synchronization primitives and locks, etc. Doing that in Go is going to be a bit interesting but probably doable. Alternatively, they might just interface with native code directly and bypass the Go ecosystem. They might even reuse some things from openjdk for that. Speaking of which, native code and JNI would need to be implemented anyway.
Writing something which is compatible with a specification is one thing, making it performant is another thing. For example it's not that hard to create a webserver from scratch but making it performant takes quite some effort.
I’ll play around with it some more and see if I can’t get some OOP pydantic-like stuff going with it. Otherwise it’s a non-starter.
https://github.com/yuin/gopher-lua
https://github.com/Shopify/go-lua
Unless you specifically need a JVM either of these will be a much more practical and mature choice for embedded scripting.
Alternatively if you prefer JS then Otto is a good choice: https://github.com/robertkrimen/otto
[1]: https://wazero.io/
(*) as long as there is a toolchain that supports using it on Wasm :P
We're using CUE to validate and transform data, as input to code gen, the basis for a DAG task engine, and more
https://cuelang.org | https://pkg.go.dev/cuelang.org/go@v0.6.0/cue | https://cuetorials.com/go-api (learn about CUE)
https://github.com/hofstadter-io/hof (where we are doing these things)
Generally, this subthread became several comments about using lang X in Go
If I want to script behavior, Lua is great. Python as well. But I’m not scripting behavior - I’m providing an engine.
I wish I had the discipline to decide I wanted to do create a long-term pet project, spend months researching what kind of project and which programming language to implement it in, and to still be motivated enough to keep actively updating it 2 years later. Also, the code comments are educational, and the write-ups are inspiring. Great stuff.
[0] from http://binstock.blogspot.com/2021/08/a-whole-new-project-jvm... linked from article
My suggestion is to find something that piques your interest for a long enough time. Thought around the "Flow" concept [1] suggests to pick something that is just within reach of your capabilities.
And perhaps try meditation to exercise building up discipline.
It also helps to ask yourself several times per day: "What would be the smartest thing to do now?", until it becomes a habit. You will then accidentally think that phrase, which gives some freedom to override other (possibly) bad habits.
The experience of adjusting difficulty and investment (you feel tired, you have emergencies.. do less, but do something, have rest days), going slow and steady versus inspiration driven is key IMO.
What is hard is accepting the near invisible small steps that don't seem to bring you closer to your goal.. that's where motivation dies.
Motivation comes and goes. Discipline shows up for work every day, rain or shine.
I’ve worked on long term projects, and it’s the discipline that lets you power through those tasks you don’t want to do. It’s required to finish anything of substance.
One thing that’s really helped me build discipline is the gym. It’s hard, I usually don’t want to go. But even on the days I don’t feel it, I go and get a workout in, even if it’s not a great workout. Even if I just go for a walk in the park or on a treadmill some days.
Once you do something consistently enough, it becomes habit, and develops its own inertia, to the point where it can become harder not to do it. I think habit and consistency are important in maintaining discipline.
So paradoxically I found that it's easier to work for 2 hours than for just 1, since the whole first hour is just getting settled in. This seems to go against the pomodoro stuff (working in 25 minute increments).
What you're saying rings true for me: it's easier to work for 2 hours vs. 1, and the pomodoro method absolutely has not worked for me the few times I've tried.
I have friends and coworkers who are the opposite though. Their barrier to the "flow state" is much lower than mine but they seem to fizzle out faster.
IMO it's all about experimenting with different approaches and finding blend one is to your taste.
It seems that flow is a state of being in which you are almost constantly rewarded for your actions. Discipline might be a way to get there.
I suppose that some people accidentally stumble into a state of flow, and others don't, but feel an urge to get there. In order to get there, they try things that give an instant reward (drugs, social media), or they try things that they think will give a big reward in the future (things you read in books or hear from wise people).
Now, the question is, how are these rewards set? Is this something you can fiddle with? Will discipline actually change what you like? I guess some people enjoy discipline by itself, which makes all this highly complicated stuff to investigate properly.
I wish somebody would unify these things but I'm running out of time in the day .
People that are able to commit time to projects like that are truly amazing.
Hey, you know a feature which I would love to see (and maybe it's already in there) -- would be the ability to "orchestrate" Java code. In other words, to be able to add external event hooks from functions/procedures/methods -- at runtime...
These event hooks, when encountered, would be able to do such things as:
* Print/pipe a debug message to an external program or log or log viewer;
* The debug printer should contain the function/procedure/method name, parameter names, and parameter values automatically (there should be functionality to have them in both the invocation and after the function/procedure/method's code is complete, prior to returning to the caller, so two possible places per function/procedure/method...);
* The ability to selectively turn on/off such events at runtime;
* The ability to add additional code which could be evaluated for every such event (also at runtime), and make the determination if the event should be processed or skipped;
* The ability to do all of the above programmatically, via API...
* Some sort of GUI which automatically imports all function/procedure/method names of a running Java program at runtime, then gives the user the ability to track/log whichever ones they want, by simply selecting them to a secondary listbox of tracked function/procedure/methods...
Now, maybe some or all of that -- is already baked in there. I didn't look at the codebase long enough to know...
But if it is in there, that's awesome! And if one or more of those features are missing, then maybe a future version maintainer or forked version maintainer might be persuaded to add them in there...
(Side note: It would be nice to have the above functionality for all programming languages!)
Anyway, as said previously, looks very cool!
Also, GraalVM/Truffle has that sort of ability today, supported for any Truffle language:
I tried to run a Java 11 jar on my M1 Mac with $JAVA_HOME pointed at a temurin-11.0.20 JVM but no such luck:
$ ./jacobin -jar my.jar
Class Format Error: Class has two package names: apple/security and com/sun/crypto/provider
detected by file: cpParser.go, line: 241
ParseAndPostClass: error parsing classes/module-info.class. Exiting.
Class Format Error: Invalid access flags of MethodParameters attribute #1 in main
detected by file: methodParser.go, line: 333
Class Format Error:
detected by file: methodParser.go, line: 109
ParseAndPostClass: error parsing my.Main. Exiting.Nonetheless, if you'd be kind enough to post the above error and the class you used into the GitHub Issues tracker [0], we'll definitely include it in our test suite and make sure whatever the problem is, it'll be corrected.
https://github.com/platypusguy/jacobin-dart (A JVM written in Dart)
https://github.com/platypusguy/jacobin-swift (Jacobin JVM written in Swift)
> I've always thought of the JVM as magical technlogy--I'm certainly not alone in that view. But in trying to learn more about it, I was greatly frustrated by the difficulty of reading the code base. As you likely know, the Hotspot JVM is open source. But reading the code is very difficult, in part because it grew organically and in part because of its unusual design, in which many actions are buried deep at the end of a long series of function calls involving unexpected classes and unusual methods, etc.
> This led me to thinking there would be value in a JVM written as a single cohesive codebase. And given that there is a 300+ page JVM specification and a reference implementation, I thought to myself, how long could this take? Two years later, and with help from two major contributors, we're still finding out! ;-)
> Eventually, we hope, it will be a fun/interesting experience for users to pop open their Go IDE and watch a Java program execute--which is why we're intent on making sure it's written in 100% go.
> In a larger context, Jacobin might eventually be useful as an embeddable JVM.
I can find references to a thread module and it clearly creates a "main" thread, but I actually can't find anywhere where it creates anything other than a main thread, nor do I see any code for task switching manually/cooperatively, or anything else like that. There's a global thread table but I can only find test code manipulating it. And the main core VM loop doesn't seem to have any concurrency in it to me.
Corrections welcome; posted fully in the spirit of Cunningham's Law as I'm curious too.
https://github.com/platypusguy/jacobin/blob/18c541820cb73bda...
I couldn't figure out what happens if you invoke a native method that has not been set up like this.
As with everything, the final 10% is 90% of the work.
But I'm also not sure that's something I'll ever need.
[0] https://jacobin.com/2022/05/jacobin-is-looking-for-a-program...
> An important factor in reducing the size of the codebase and executable is that Jacobin relies on Go’s built-in memory management to perform garbage collection, and so it contains no GC code.
I don't see how you can't see it.
This is pretty cool, imo.
As long as the language is GC agnostic, and just cares for stuff being collected, and not for some particular exposed semantics of the GC, it should be ok.
Andrew's Java skills are at a different level. I only briefly met him once, but he used to be a core contributor to Oracle's Java magazine. 80% of the "Unix greybeard" type advanced Java knowledge I have is due to his articles.
Happy to see he's still building. Thanks Andrew!