JRuby: Ruby on the Java virtual machine
In this lesson your code does not run on CRuby. Every cell goes to JRuby – the Ruby on the Java virtual machine (JVM) from lesson 89. A browser has no JVM, so this JRuby was translated from Java to JavaScript with TeaVM, and it runs in a Web Worker of its own. It is loaded only for this lesson: about 7.2 MB, the first time.
Ask it who it is:
[RUBY_ENGINE, JRUBY_VERSION, RUBY_VERSION]"jruby", JRuby's own version, and the Ruby it speaks: 4.0, the same language as the CRuby of the rest of the course. What CRuby cannot do: JRuby knows Java's classes. java.util.ArrayList is a Java list – and << works on it as on an Array:
list = java.util.ArrayList.new
list << "Speck" << "apfel" << "Bacon"
java.util.Collections.sort(list) { |a, b| a.downcase <=> b.downcase }
list.to_aCollections.sort is Java. It wants a Comparator, a Java object with one method that compares two things. JRuby turns the Ruby block into one. And Java's names fit into Ruby: Java's isEmpty() may be called is_empty or empty?, nextToken() is next_token – you will see more of them below.
A Java library is a Ruby library
Maven Central, the big library shelf of the Java world, holds over half a million libraries, and JRuby can use every one of them. ZXing (“zebra crossing”) makes and reads barcodes; many Android apps scan with it. This JRuby brings ZXing along. A web address as a QR code:
java_import com.google.zxing.qrcode.QRCodeWriter
java_import com.google.zxing.BarcodeFormat
url = "https://letsruby.com"
qr = QRCodeWriter.new.encode(url, BarcodeFormat::QR_CODE, 0, 0)
rows = (0...qr.height).step(2).map do |y|
(0...qr.width).map do |x|
top = qr.get(x, y)
bottom = y + 1 < qr.height && qr.get(x, y + 1)
if top && bottom then "█"
elsif top then "▀"
elsif bottom then "▄"
else " "
end
end.join
end
puts rowsPoint your phone's camera at it – it opens this course. Each line of the output holds two rows of the code: ▀ is a dot on top, ▄ one below, █ both.
To be fair: CRuby has a gem for QR codes too (rqrcode, pure Ruby). The point is a different one: whatever the Java world has written is one java_import away. (In this browser JRuby only the Java classes listed when it was built are there; on your computer, all of them.)
A big JSON file: every earthquake for a month
The U.S. Geological Survey (USGS) publishes every earthquake its seismometers record, as GeoJSON. Here is a snapshot of 17 October 2026: 7.3 MB, 10,224 earthquakes in 30 days, public domain. It lies next to your code as data/all_month.geojson. JRuby's json is the same gem as CRuby's – only its parser is written in Java instead of C:
require "json"
t = Time.now
quakes = JSON.parse(File.read("data/all_month.geojson"))["features"]
puts "#{quakes.size} quakes in #{((Time.now - t) * 1000).round} ms"Each earthquake is a Hash: q["properties"]["mag"] is its magnitude, q["properties"]["place"] where it was. The five strongest:
quakes.max_by(5) { |q| q["properties"]["mag"].to_f }
.map { |q| "M #{q["properties"]["mag"]} #{q["properties"]["place"]}" }And where the earth shakes most often – the part after the last comma of the place:
quakes.map { |q| q["properties"]["place"].to_s.split(", ").last }
.tally.max_by(5) { |_, n| n }Alaska and California lead because the USGS has the most seismometers there; it hears even tiny quakes. Now the very same parse on CRuby (ruby.wasm), the Ruby the rest of this course runs on. The label above each output says which Ruby ran the cell, and how long it took:
require "json"
t = Time.now
quakes = JSON.parse(File.read("data/all_month.geojson"))["features"]
puts "#{quakes.size} quakes in #{((Time.now - t) * 1000).round} ms"On an 8-core server in headless Chromium, CRuby parsed the file in 96–208 ms, JRuby in 0.8–1.0 s. In the browser CRuby is faster: its JSON parser is C, compiled to WebAssembly; this JRuby is Java translated to JavaScript, without the JIT compiler that makes Java fast on a real JVM. Speed is not why you would pick JRuby in a browser – the libraries are.
Jackson: JSON as a stream
Most Java programs read JSON with Jackson. It does not build one big Hash: it hands you the file piece by piece, as tokens – START_OBJECT, FIELD_NAME “mag”, VALUE_NUMBER_FLOAT 5.2 … The cell counts the quakes of magnitude 5 or more, on the smaller file data/4.5_month.geojson (only the 622 quakes from 4.5 up, 0.4 MB). token.numeric? is Java's isNumeric():
java_import com.fasterxml.jackson.core.JsonFactory
parser = JsonFactory.new.create_parser(File.read("data/4.5_month.geojson"))
count = 0
while (token = parser.next_token)
if parser.current_name == "mag" && token.numeric?
count += 1 if parser.double_value >= 5
end
end
countEvery next_token is a trip from Ruby into Java and back – tens of thousands of trips for this file. The same loop written in Java, which this lesson brings along as Lesson::Quakes, makes the trip once:
public static int countAtLeast(String json, double min) throws IOException {
int n = 0;
JsonParser p = new JsonFactory().createParser(json);
JsonToken t;
while ((t = p.nextToken()) != null) {
if (t == JsonToken.FIELD_NAME && "mag".equals(p.currentName())) {
if (p.nextToken().isNumeric() && p.getDoubleValue() >= min) n++;
}
}
return n;
}Java::Lesson::Quakes.count_at_least(File.read("data/4.5_month.geojson"), 5)The same 173 – and look at the times above the outputs. Measured here: the Ruby loop 549–756 ms, the Java loop 39–59 ms, about 9–19 times faster. That is the lesson of this part: when a loop is hot, let the Java library do the looping. (Ruby calls countAtLeast by its Ruby name, count_at_least.)
Threads
On a JVM, Ruby threads really run at the same time, each on its own processor core. That makes them fast – and lets them trample on each other. Four threads, each adding 1 a hundred times, with a short sleep between reading and writing:
count = 0
threads = 4.times.map do
Thread.new do
100.times do
v = count
sleep 0.001
count = v + 1
end
end
end
threads.each(&:join)
count100, not 400. All four threads read the same count, sleep, and write back their old value plus 1 – three of every four additions get lost. A Mutex lets one thread at a time through:
count = 0
lock = Mutex.new
threads = 4.times.map do
Thread.new do
100.times do
lock.synchronize do
v = count
sleep 0.001
count = v + 1
end
end
end
end
threads.each(&:join)
count400. Java brings counters made for this in java.util.concurrent: an AtomicLong adds without a lock and without losing anything. increment_and_get is Java's incrementAndGet:
count = java.util.concurrent.atomic.AtomicLong.new(0)
threads = 4.times.map do
Thread.new { 50_000.times { count.increment_and_get } }
end
threads.each(&:join)
count.getTo be honest about the browser: these threads take turns on one JavaScript thread, as CRuby's do. The race above comes from the sleep, and CRuby shows it just the same. What changes on a real JVM is in the box below.
JRuby 10.1.2 on Java 21 against CRuby 4.0.6, measured on an 8-core server (ranges of 20 runs, 5 for the start, 8 for Jackson; the first runs, while the JIT compiler warms up, are given apart):
- Starting:
jruby -e 'puts 1'takes 2.5–2.8 s,ruby53–65 ms. The JVM needs a moment. - 4 threads × fib(27): CRuby 77–100 ms one after another and 77–105 ms in threads – no gain, the GVL lets one thread at a time run Ruby. JRuby: the first runs take 607–723 ms, then the JIT compiler has warmed up: 18–39 ms one after another, 5.5–17 ms in 4 threads, mostly about 10 ms. (CRuby with YJIT: 16–20 / 16–24 ms.)
- The race without any sleep (
4.times.map { Thread.new { 50_000.times { count += 1 } } }): JRuby ends between 66,934 and 128,453 instead of 200,000, CRuby always at 200,000. Real threads need a Mutex or an AtomicLong. - A float loop (a Mandelbrot set, 200 × 200 points): CRuby 341–399 ms, YJIT 198–244 ms; JRuby 573 ms the first time, then 55–358 ms – often faster, but unsteady.
- JSON.parse of the 7.3 MB file: about the same, CRuby 40–60 ms (60 ms the first time, then 40–48 ms), JRuby 38–43 ms after warm-up (its first three runs: 148, 95 and 63 ms). Jackson in 4 threads reads the file 4 times in 118–194 ms, one after another 469–553 ms (the first time 235 and 977 ms).
So: after a warm-up, JRuby is fast and uses every core – that is why servers run it. Install it with rbenv install jruby-10.1.2.0 (it needs Java 21); a Java library comes in with require "path/to/jackson-core.jar", or as a dependency through the jar-dependencies gem. In lesson 89, threads_in_parallel? said so – here are the numbers.
Bonus: desktop windows with Glimmer
On your computer JRuby also brings Java's desktop toolkit, Swing. With the Glimmer DSL a window is a few nested blocks, and observe keeps the label in step with the fox (data binding). TeaVM's JRuby has no Swing – but CheerpJ by Leaning Technologies has: a whole Java virtual machine, compiled to WebAssembly. On it runs JRuby 9.4 – the official jruby-complete, with just one class adapted for CheerpJ –, an older JRuby that speaks Ruby 3.1, and only as an interpreter. That comes at a price: about 40 MB (CheerpJ's own part comes from their server, cjrtnc.leaningtech.com), and starting takes 20–40 s – on a fast 8-core server 27 s (JRuby 14–15 s, then Glimmer 12–13 s), on a laptop or phone longer. Nothing of it loads before you click:

With JRuby installed: gem install glimmer-dsl-swing, put this into fox.rb and run jruby fox.rb – a real window, once JRuby has started and loaded Glimmer (the start alone takes the 2.5–2.8 s from above):
require "glimmer-dsl-swing"
include Glimmer
class Fox
attr_accessor :bacon
def initialize = @bacon = 0
end
fox = Fox.new
jframe("Chunky Bacon") {
jpanel {
@label = jlabel("Bacon: 0")
jbutton("Feed the fox") {
on_action_performed { fox.bacon += 1 }
}
}
}.show
observe(fox, :bacon) { |n| @label.text = "Bacon: #{n}" }strong_quakes(quakes, magnitude): it returns how many quakes have at least that magnitude. The last line of the cell, strong_quakes(quakes, 5), counts those of magnitude 5 and up. The check is done by CRuby – which then runs your code as well, so you see whether both Rubies agree.require "json"
def strong_quakes(quakes, magnitude)
# count the quakes with mag >= magnitude
end
quakes = JSON.parse(File.read("data/all_month.geojson"))["features"]
strong_quakes(quakes, 5)