Created
November 11, 2025 21:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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