SlideShare une entreprise Scribd logo
1  sur  55
Télécharger pour lire hors ligne
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

Contenu connexe

En vedette

En vedette (7)

Threads in Ruby (Basics)
Threads in Ruby (Basics)Threads in Ruby (Basics)
Threads in Ruby (Basics)
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
 
Threading and Concurrency in Ruby
Threading and Concurrency in RubyThreading and Concurrency in Ruby
Threading and Concurrency in Ruby
 
Treading the Rails with Ruby Shoes
Treading the Rails with Ruby ShoesTreading the Rails with Ruby Shoes
Treading the Rails with Ruby Shoes
 
Multi-threaded web crawler in Ruby
Multi-threaded web crawler in RubyMulti-threaded web crawler in Ruby
Multi-threaded web crawler in Ruby
 
Actors and Threads
Actors and ThreadsActors and Threads
Actors and Threads
 
The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017The Top Skills That Can Get You Hired in 2017
The Top Skills That Can Get You Hired in 2017
 

Similaire à Ruby thread safety first

what every web and app developer should know about multithreading
what every web and app developer should know about multithreadingwhat every web and app developer should know about multithreading
what every web and app developer should know about multithreading
Ilya Haykinson
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
ppparthpatel123
 
How to discover the Ruby's defects with web application
How to discover the Ruby's defects with web applicationHow to discover the Ruby's defects with web application
How to discover the Ruby's defects with web application
Hiroshi SHIBATA
 
Zookeeper big sonata
Zookeeper  big sonataZookeeper  big sonata
Zookeeper big sonata
Anh Le
 
Nzpug welly-cassandra-02-12-2010
Nzpug welly-cassandra-02-12-2010Nzpug welly-cassandra-02-12-2010
Nzpug welly-cassandra-02-12-2010
aaronmorton
 

Similaire à Ruby thread safety first (20)

what every web and app developer should know about multithreading
what every web and app developer should know about multithreadingwhat every web and app developer should know about multithreading
what every web and app developer should know about multithreading
 
Top 30 Node.js interview questions
Top 30 Node.js interview questionsTop 30 Node.js interview questions
Top 30 Node.js interview questions
 
The Ruby Guide to *nix Plumbing: Hax0R R3dux
The Ruby Guide to *nix Plumbing: Hax0R R3duxThe Ruby Guide to *nix Plumbing: Hax0R R3dux
The Ruby Guide to *nix Plumbing: Hax0R R3dux
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
concurrency
concurrencyconcurrency
concurrency
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
How to discover the Ruby's defects with web application
How to discover the Ruby's defects with web applicationHow to discover the Ruby's defects with web application
How to discover the Ruby's defects with web application
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
Zookeeper big sonata
Zookeeper  big sonataZookeeper  big sonata
Zookeeper big sonata
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Parallel Programming: Beyond the Critical Section
Parallel Programming: Beyond the Critical SectionParallel Programming: Beyond the Critical Section
Parallel Programming: Beyond the Critical Section
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
 
Thread priorities in java
Thread priorities in javaThread priorities in java
Thread priorities in java
 
Pfm technical-inside
Pfm technical-insidePfm technical-inside
Pfm technical-inside
 
MERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel ProgrammingMERIMeeting du 27 mai 2014 - Parallel Programming
MERIMeeting du 27 mai 2014 - Parallel Programming
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Lec7
Lec7Lec7
Lec7
 
Nzpug welly-cassandra-02-12-2010
Nzpug welly-cassandra-02-12-2010Nzpug welly-cassandra-02-12-2010
Nzpug welly-cassandra-02-12-2010
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Ruby thread safety first