Skip to content

Commit

Permalink
Fix race condition in CommandMap#prefix
Browse files Browse the repository at this point in the history
`PrefixProvider#[]` could return `nil` in multi-threaded scenarios due to a race
condition involving `||=`, which is not an atomic operation in JRuby.

The test that I added failed with JRuby 9.0.4.0 before the fix; now it passes.
  • Loading branch information
mattbrictson committed Jan 29, 2016
1 parent 29f75ad commit c2ce73e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
2 changes: 0 additions & 2 deletions lib/sshkit/command_map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ def initialize

def [](command)
@storage[command] ||= []

@storage[command]
end
end

Expand Down
9 changes: 9 additions & 0 deletions test/unit/test_command_map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,14 @@ def test_indifferent_prefix
assert_equal map[:rake], "/home/vagrant/.rbenv/bin/rbenv exec bundle exec rake"
end

def test_prefix_initialization_is_thread_safe
map = CommandMap.new
threads = Array.new(3) do
Thread.new do
(1..1_000).each { |i| assert_equal([], map.prefix[i.to_s]) }
end
end
threads.each(&:join)
end
end
end

0 comments on commit c2ce73e

Please sign in to comment.