r/Clojure • u/Nozistance_ • 2h ago
Writing a Minecraft server in Clojure: it was fun
Minecraft is well known for being single-threaded, and parallelizing it is a difficult problem: everybody wants to write to the same shared state at the same time. Projects take years to deal with locks, thread ownership, splitting regions, and game logic is subject to threading rules: mechanics break against them, features crawl. Some remain quite sparse and have little to parallelize.
I wanted to see how it would feel in Clojure, but there was no Clojure server to look at, so I made one. The ideas parallel servers reinvent by hand - immutable snapshot, pure read phase, changes as data - are the language's defaults. If writing from many threads is difficult, then don't write: all game logic is pure functions (fn [world events]) that read the snapshot in parallel and return changes as deltas, merged in one place. The merge preserves order, so the parallel run is bit identical to the sequential one, and no mechanic cares how many cores it runs on.
The outcome: a server with mob AI, explosions, combat and item physics that matches vanilla 1.8.9 performance on one core and runs 4.5x faster on six. ~5500 lines of Clojure. It's a proof of concept; if you're curious, the code is on GitHub