SlideShare a Scribd company logo
Text
!
THREAD
SAFETY
FIRST
Emily Stolfo
Ruby Engineer at , Adjunct Faculty at Columbia
@EmStolfo
There is no such thing as
thread-safe Ruby code.
Ruby Engineer at
Adjunct Faculty at Columbia
Expert
Emily Stolfo
require 'set'
members = Set.new
threads = []
200.times do |n|
threads << Thread.new do
if n % 2 == 0
members << n
else
members.first.nil?
end
end
end
threads.each(&:join)
Demo code
Inconsistent bug?
2.0 with 200 threads
JRuby with 10 threads
JRuby with 200 threads
✔
𝙭
✔
1. Concurrency in Ruby
! THREAD SAFETY FIRST
3. Testing concurrency
2. Writing thread-safe code
CONCURRENCY IN RUBY
There are different
Ruby implementations.
Threads are like
music.
GIL
green thread
native (OS) thread
ruby 1.8
Threads and Ruby
Instruments: OS threads
Notes: green threads
Conductor: GIL
ruby 1.9+
Instruments: OS threads
Notes: green threads
Conductor: GIL
Threads and Ruby
JRuby
Instruments: OS threads
Notes: green threads
Threads and Ruby
Different Rubies?
Different semantics.
Our code
sometimes works by
sheer luck.
You’re lucky your code
hasn’t run on JRuby.
You’re lucky
there is a GIL.
Example:
MongoDB Ruby driver
and Replica Sets
MongoDB Replica Set Creation
MongoDB Replica Set
MongoDB Replica Set Failure
MongoDB Replica Set Recovery
MongoDB Replica Set Recovered
Mutable shared state.
class ReplicaSetClient
def initialize
@nodes = Set.new
end
...
def connect_to_nodes
seed = valid_node
seed.node_list.each do |host|
node = Node.new(host)
@nodes << node if node.connect
end
end
def choose_node(type)
@nodes.detect { |n| n.type == type }
end
end
Ruby driver
class ReplicaSetClient
def initialize
@nodes = Set.new
end
...
def connect_to_nodes
seed = valid_node
seed.node_list.each do |host|
node = Node.new(host)
@nodes << node if node.connect
end
end
def choose_node(type)
@nodes.detect { |n| n.type == type }
end
end
Potential concurrency bug
(RuntimeError)
"can't add a new key into
hash during iteration"
We often use
hashes as caches.
Hashes and their
derivatives are not
thread-safe in JRuby.
!
How do we write this
code thread-safely?
WRITING
THREAD-SAFE CODE
Shared data:
Avoid across threads.
If you can’t avoid shared
data, at least avoid
shared mutable data.
If you can’t avoid
shared mutable data,
use concurrency primitives.
The top 2
concurrency primitives
class ReplicaSetClient
def initialize
@nodes = Set.new
@connect_mutex = Mutex.new
end
...
def connect_to_nodes
seed = valid_node
seed.node_list.each do |host|
node = Node.new(host)
@connect_mutex.synchronize do
@nodes << node if node.connect
end
end
end
def choose_node(type)
@connect_mutex.synchronize do
@nodes.detect { |n| n.type == type }
end
end
end
1. Mutex
class ReplicaSetClient
def initialize
@nodes = Set.new
@connect_mutex = Mutex.new
end
...
def connect_to_nodes
seed = valid_node
seed.node_list.each do |host|
node = Node.new(host)
@connect_mutex.synchronize do
@nodes << node if node.connect
end
end
end
def choose_node(type)
@connect_mutex.synchronize do
@nodes.detect { |n| n.type == type }
end
end
end
1. Mutex
Use to isolate code
that should be
executed by at most
one thread at a time.
shared
replica
set
state
update
A mutex is not magic.
Avoid locking
around I/O.
class ReplicaSetClient
def initialize
@nodes = Set.new
@connect_mutex = Mutex.new
end
...
def connect_to_nodes
seed = valid_node
seed.node_list.each do |host|
node = Node.new(host)
@connect_mutex.synchronize do
@nodes << node if node.connect
end
end
end
def choose_node(type)
@connect_mutex.synchronize do
@nodes.detect { |n| n.type == type }
end
end
end
1. Mutex
network
I/O
class ReplicaSetClient
def initialize
@nodes = Set.new
@connect_mutex = Mutex.new
end
...
def connect_to_nodes
seed = valid_node
seed.node_list.each do |host|
node = Node.new(host)
@connect_mutex.synchronize do
@nodes << node
end if node.connect
end
end
def choose_node(type)
@connect_mutex.synchronize do
@nodes.detect { |n| n.type == type }
end
end
end
1. Mutex
network
I/O
Consider resources.
Ex: Thundering herd
Thundering herd
n threads are woken up after waiting on something,
but only 1 can continue. Waste of system resources
to wake up n threads.
Consider your system.
Ex: Queued requests
App
server
Think systemically.
n threads are waiting to write to the replica set
primary. The primary is flooded with requests when
the replica set state is refreshed.
App
server
2. Condition Variable
Use to communicate between threads.
class Pool
def initialize
@socket_available = ConditionVariable.new
...
end
def checkout
loop do
@lock.synchronize do
if @available_sockets.size > 0
socket = @available_sockets.next
return socket
end
@socket_available.wait(@lock)
end
end
end
def checkin(socket)
@lock.synchronize do
@available_sockets << socket
@socket_available.
end
end
end
Condition Variable
broadcast
Why is this
a waste of
system
resources?
class Pool
def initialize
@socket_available = ConditionVariable.new
...
end
def checkout
loop do
@lock.synchronize do
if @available_sockets.size > 0
socket = @available_sockets.next
return socket
end
@socket_available.wait(@lock)
end
end
end
def checkin(socket)
@lock.synchronize do
@available_sockets << socket
@socket_available.
end
end
end
Condition Variable
signal
Only one
thread
can
continue
TESTING CONCURRENCY
Testing
1. Test with different implementations.
2. Test with a ton of threads.
3. Use patterns for precision.
require 'set'
members = Set.new
threads = []
10.times do |n|
threads << Thread.new do
if n % 2 == 0
members << n
else
members.first.nil?
end
end
end
threads.each(&:join)
Test with a ton of threads.
require 'set'
members = Set.new
threads = []
200.times do |n|
threads << Thread.new do
if n % 2 == 0
members << n
else
members.first.nil?
end
end
end
threads.each(&:join)
Test with a ton of threads.
Use synchronization
methods if you need
more precision.
ex: rendezvous / barrier
pattern
Concurrency in Ruby
Know your implementations.
!
Know your concurrency primitives.
!
Know your code.
”thread-safe JRuby 1.7.4 code”
!
Thanks
Emily Stolfo
@EmStolfo

More Related Content

PDF
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger
 
PDF
Introduction to Cassandra
aaronmorton
 
PDF
Archeology for Entertainment, or Checking Microsoft Word 1.1a with PVS-Studio
Andrey Karpov
 
PDF
Introducing Elixir and OTP at the Erlang BASH
devbash
 
PDF
An introduction to Rust: the modern programming language to develop safe and ...
Claudio Capobianco
 
PDF
JRuby @ Boulder Ruby
Nick Sieger
 
ODP
Clojure: Practical functional approach on JVM
sunng87
 
ODP
Biopython
Karin Lagesen
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger
 
Introduction to Cassandra
aaronmorton
 
Archeology for Entertainment, or Checking Microsoft Word 1.1a with PVS-Studio
Andrey Karpov
 
Introducing Elixir and OTP at the Erlang BASH
devbash
 
An introduction to Rust: the modern programming language to develop safe and ...
Claudio Capobianco
 
JRuby @ Boulder Ruby
Nick Sieger
 
Clojure: Practical functional approach on JVM
sunng87
 
Biopython
Karin Lagesen
 

Viewers also liked (7)

PPT
Threads in Ruby (Basics)
varunlalan
 
ODP
Concurrent Programming with Ruby and Tuple Spaces
luccastera
 
PDF
Threading and Concurrency in Ruby
Tim Raymond
 
PDF
Treading the Rails with Ruby Shoes
Eleanor McHugh
 
PDF
Multi-threaded web crawler in Ruby
Polcode
 
KEY
Actors and Threads
mperham
 
PDF
The Top Skills That Can Get You Hired in 2017
LinkedIn
 
Threads in Ruby (Basics)
varunlalan
 
Concurrent Programming with Ruby and Tuple Spaces
luccastera
 
Threading and Concurrency in Ruby
Tim Raymond
 
Treading the Rails with Ruby Shoes
Eleanor McHugh
 
Multi-threaded web crawler in Ruby
Polcode
 
Actors and Threads
mperham
 
The Top Skills That Can Get You Hired in 2017
LinkedIn
 
Ad

Similar to Ruby thread safety first (20)

PDF
Concurrency: Rubies, Plural
Eleanor McHugh
 
PDF
Concurrency: Rubies, plural
ehuard
 
PDF
Concurrecy in Ruby
Vesna Doknic
 
PPTX
Guild Prototype
Koichi Sasada
 
PDF
Ruby's Concurrency Management: Now and Future
Koichi Sasada
 
PDF
Introduction to Ruby threads
Luong Vo
 
KEY
Concurrent programming with Celluloid (MWRC 2012)
tarcieri
 
PDF
Bringing Concurrency to Ruby - RubyConf India 2014
Charles Nutter
 
PPTX
Finding concurrency problems in core ruby libraries
louisadunne
 
PPT
Threads
Kavita Kanojiya
 
KEY
Ruby Concurrency Realities
Mike Subelsky
 
PDF
Multithread Your Application
Andy Su
 
KEY
Ruby Concurrency and EventMachine
Christopher Spring
 
KEY
Concurrency in ruby
Marco Borromeo
 
KEY
A Case of Accidental Concurrency
Sean Cribbs
 
KEY
Ruby 1.9 Fibers
Kevin Ball
 
PDF
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Eleanor McHugh
 
PDF
Concurrency
ehuard
 
PDF
How To Write Middleware In Ruby
SATOSHI TAGOMORI
 
PDF
Dataflow: Declarative concurrency in Ruby
Larry Diehl
 
Concurrency: Rubies, Plural
Eleanor McHugh
 
Concurrency: Rubies, plural
ehuard
 
Concurrecy in Ruby
Vesna Doknic
 
Guild Prototype
Koichi Sasada
 
Ruby's Concurrency Management: Now and Future
Koichi Sasada
 
Introduction to Ruby threads
Luong Vo
 
Concurrent programming with Celluloid (MWRC 2012)
tarcieri
 
Bringing Concurrency to Ruby - RubyConf India 2014
Charles Nutter
 
Finding concurrency problems in core ruby libraries
louisadunne
 
Ruby Concurrency Realities
Mike Subelsky
 
Multithread Your Application
Andy Su
 
Ruby Concurrency and EventMachine
Christopher Spring
 
Concurrency in ruby
Marco Borromeo
 
A Case of Accidental Concurrency
Sean Cribbs
 
Ruby 1.9 Fibers
Kevin Ball
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Eleanor McHugh
 
Concurrency
ehuard
 
How To Write Middleware In Ruby
SATOSHI TAGOMORI
 
Dataflow: Declarative concurrency in Ruby
Larry Diehl
 
Ad

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Future of Artificial Intelligence (AI)
Mukul
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Software Development Methodologies in 2025
KodekX
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Simple and concise overview about Quantum computing..pptx
mughal641
 

Ruby thread safety first