Created
October 11, 2016 08:23
-
-
Save kalsan/cdecebb51830075af7bfdc058a4de1a1 to your computer and use it in GitHub Desktop.
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
| # This file demonstrates that attributes created by class_attribute (in Rails' ActiveSupport) are not thread-safe. | |
| # On my system, the test fails sometimes when setting count to 1_000 and always with a count of 10_000. | |
| # Expected exception: NameError: Undefined method setting for 'BugTest::MyClass' | |
| # Note: Occurs on jruby only. | |
| # See issue https://github.com/rails/rails/issues/26758 | |
| begin | |
| require 'bundler/inline' | |
| rescue LoadError => e | |
| $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' | |
| fail e | |
| end | |
| gemfile(true) do | |
| source 'https://rubygems.org' | |
| gem 'rails', github: 'rails/rails' | |
| end | |
| require 'active_support' | |
| require 'active_support/core_ext/object/blank' | |
| require 'minitest/autorun' | |
| class BugTest < Minitest::Test | |
| # Boot phase: Single-threaded | |
| class MyClass | |
| class_attribute :setting | |
| end | |
| def test_multithreaded | |
| puts "Ruby version: #{RUBY_VERSION}" | |
| puts "Ruby engine: #{RUBY_ENGINE}" | |
| puts "ActiveSupport: #{ActiveSupport::VERSION::STRING}" | |
| # Program up and running: This must be allowed to be multi-threaded IMHO | |
| # On my system, failure occurs sometimes with 1'000 and always with 10'000 threads. | |
| count = 10_000 | |
| ts = [] | |
| count.times do |i| # Spawning threads | |
| ts << Thread.new do | |
| sleep(rand) # Random sleep (0-1 sec.) to avoid accidental sequential behavior | |
| MyClass.setting = i # Exception occurs on this line. | |
| sleep(rand) | |
| end | |
| end | |
| count.times do |i| | |
| ts[i].join # Joining threads and termination | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment