๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Ruby Ractor Shareable Objects

Most objects stay on one side of a ractor boundary. A shareable object is frozen deeply enough to cross that boundary and be read inside a ractor.

Checking and making shareable

shareable? answers false for a plain nested array. After make_shareable runs, the shareable verdict turns true and both arrays report frozen.

Warning[:experimental] = false
words = ["red", ["dark", "light"]]
puts Ractor.shareable?(words)
Ractor.make_shareable(words)
puts Ractor.shareable?(words)
puts words.frozen?
puts words[1].frozen?

Shareable from the start

A frozen string, a number, and a symbol are shareable without any preparation. A plain string is not.

Warning[:experimental] = false
word = "ruby".freeze
puts Ractor.shareable?(word)
puts Ractor.shareable?(42)
puts Ractor.shareable?(:ready)
puts Ractor.shareable?("plain")

Reading a shareable hash inside a ractor

The hash sits in a constant after make_shareable freezes it. The block reads the theme through the constant name, and take returns it.

Warning[:experimental] = false
SETTINGS = { theme: "dark", level: 3 }
Ractor.make_shareable(SETTINGS)
ractor = Ractor.new do
  SETTINGS[:theme]
end
puts ractor.take
puts SETTINGS.frozen?

make_shareable returns the object

make_shareable returns the same object it froze. The returned array reports frozen and still prints its values.

Warning[:experimental] = false
pair = Ractor.make_shareable(["tea", "juice"])
puts pair.frozen?
p pair

Example

Warning[:experimental] = false
MENU = { drinks: ["tea", "juice"], count: 2 }
Ractor.make_shareable(MENU)
ractor = Ractor.new do
  MENU[:drinks].length
end
puts ractor.take
puts MENU[:drinks].frozen?
puts Ractor.shareable?(MENU)

Key points

  • Ractor.shareable? answers whether an object can be read inside a ractor.
  • Ractor.make_shareable freezes an object along with everything nested inside it.
  • make_shareable freezes the original object in place and returns it.
  • Numbers, symbols, and frozen strings are shareable from the start.
  • A ractor block can read a shareable object through a constant name.

In this example, make_shareable freezes the MENU hash and the array inside it. A ractor reads the drinks list through the constant and returns its length. The last lines confirm the nested array is frozen and the whole hash is shareable.

Note

The first line of every ractor program here turns the experimental warning off.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does Ractor.make_shareable do to the original object it is given?