Skip to content

Instantly share code, notes, and snippets.

@rachel-carvalho
Created November 11, 2025 21:30
Show Gist options
  • Select an option

  • Save rachel-carvalho/25b8bb351e3e16ab1532f08fd5df686a to your computer and use it in GitHub Desktop.

Select an option

Save rachel-carvalho/25b8bb351e3e16ab1532f08fd5df686a to your computer and use it in GitHub Desktop.
This shows how a singleton instance variable is shared across threads and can cause unexpected results
# frozen_string_literal: true
require 'singleton'
class Fruit
include Singleton
def config
@config ||= {}
end
def set(text)
config[:text] = text
end
end
t = Thread.new do
Fruit.instance.set 'banana'
puts 'text after first thread set (we expect banana)'
puts Fruit.instance.config[:text]
sleep 4
puts 'text after first thread sleep (we expect banana, but it will be coconut)'
puts Fruit.instance.config[:text]
end
Thread.new do
sleep 2
Fruit.instance.set 'coconut'
puts 'text after second thread set (we expect coconut)'
puts Fruit.instance.config[:text]
end
t.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment