SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
CONCURRENCY
&
RUBY
Rocky	Jaiswal
RubyConf	India	2013
WHY	CONCURRENCY?
ABOUT	ME
Learning	programming	for	the	last	11	years
Did	Java	for	around	8	years
Started	learning	Ruby	~3	years	back
♥	Ruby
♥	the	Ruby	community
Also	learning	some	CoffeeScript	and	Scala
http://rockyj.in
@whatsuprocky
CONCURRENCY?
Concurrency	is	when	two	tasks	can	start,	run,	and
complete	in	overlapping	time	periods
Concurrency	can	be	implemented	even	in	single
processing	units	to	speed	things	up
Concurrency	is	non-deterministic
Whereas	a		parallel	program	is	one	that	merely	runs	on
multiple	processors,	with	the	goal	of	hopefully	running
faster	than	it	would	on	a	single	CPU
THREADS	VS	PROCESSESS
Threads	are	light	weight	processes	that	run	in	the	same
memory	context
Ruby	has	Green	Threads	which	are	managed	by	the	Ruby
process
JRuby	has	real	OS	thread	that	run	parallel	to	the	parent
thread
THREADS	IN	RUBY
SAMPLE	UNICORN	SETUP
15	Unicorns	=	15	Processes
1	Unicorn	Process	~=	150	MB
15	Processes	~=	2	GB	RAM*
Scaling	this	means	more	processes	=	more	memory	=
more	money
Also,	If	you	are	CPU	bound	you	want	to	use	no	more
unicorn	processes	than	you	have	cores,	otherwise	you
overload	the	system	and	slow	down	the	scheduler.
CONCURRENCY	IS	GOOD
JRuby	+	Puma	/	Torquebox
High-Scalability	with	less	memory
Resque	/	Sidekiq
More	workers	and	faster	processing	with	less	memory
SO	IS	IT	ALL	DOOM	AND	GLOOM?
No!
Most	Rails	applications	are	IO	bound
With	MRI	you	are	always	thread	safe
MRI	is	getting	faster	and	GC	is	getting	better
Processes	management	is	optimized
Passenger	is	using	a	hybrid	-	evented	+	threaded	/
process	architecture
THREAD-SAFETY
LET	ME	GIVE	YOU	A	DEMO
Appending	to	Arrays:
MRI	Version
vs
JRuby	Version
DEMO
RUN	CODE	ON	MRI	&	JRUBY
array	=	[]
5.times.map	do
		Thread.new	do	#Init	5	threads
				1000.times	do
						array	<<	nil	#In	each	thread	add	1000	elements	to	the	Ar
				end
		end
end.each(&:join)
puts	array.size
EVEN	APPENDING	TO	ARRAYS	IS
NOT	THREAD	SAFE!
WHAT	ABOUT	RAILS
config.threadsafe!
	def	threadsafe!
		@preload_frameworks	=	true
		@cache_classes						=	true
		@dependency_loading	=	false
		@allow_concurrency		=	true
		self
end
JRUBY	ON	RAILS
DEMO
BAD	COUNTER	CODE
	class	PagesController	<	ApplicationController
		@counter	=	0
		class	<<	self
				attr_accessor	:counter
		end
		#Classic	read-modify-write	problem
		def	index
				counter	=	self.class.counter	#	read
				sleep(0.1)
				counter	+=	1	#update
				sleep(0.1)
				self.class.counter	=	counter	#	write
				users	=	User.all
				puts	"-----------"	+	self.class.counter.to_s	+	"------------"
		end
end
UGLY	SYNCHRONIZED	CODE
	class	PagesController	<	ApplicationController
		@counter	=	0
		@semaphore	=	Mutex.new
		class	<<	self
				attr_accessor	:counter
				attr_accessor	:semaphore
		end
		def	index
				#counter	=	self.class.counter	#	read
				sleep(0.1)
				self.class.semaphore.synchronize	{
						self.class.counter	+=	1	#update
				}
				sleep(0.1)
				#self.class.counter	=	counter	#	write
				users	=	User.all
				puts	"-----------"	+	self.class.counter.to_s	+	"------------"
		end
end
RAILS	4	IS	CONCURRENCY
ENABLED	BY	DEFAULT
CONCURRENCY	INTRODUCES
Race	Conditions
Deadlocks
Starvation
etc.
BUT	GIVES	YOU
Speed
Less	Memory	Usage
SAFE	CONCURRENCY
Don't	do	it.
If	you	must	do	it,	don't	share	data	across
threads.
If	you	must	share	data	across	threads,	don't
share	mutable	data.
If	you	must	share	mutable	data	across	threads,
synchronize	access	to	that	data.
THREAD	SAFETY	IN	JRUBY
LOCKS
ATOMICITY
IMMUTABILITY
ATOMIC	COUNTER
java_import	'java.util.concurrent.atomic.AtomicInteger'
class	PagesController	<	ApplicationController
		@counter	=	AtomicInteger.new(1)	
		
		class	<<	self
				attr_accessor	:counter
		end
		def	index
				sleep(0.1)
				counter	=	self.class.counter.getAndIncrement()	#update
				sleep(0.1)
				users	=	User.all
				puts	"-----------------"	+	counter.to_s	+	"-----------------"
		end
end
ALL	THIS	SUCKS!
95%	of	syncronized	code	is	broken.	The	other	5%	is
written	by	Brian	Goetz.	-	Venkat	Subramaniam
ENTER	ACTOR
THE	ACTOR	MODEL
Introduced	by	Carl	Hewitt	in	1973
Contributions	by	a	lot	of	scholars	and	universities
Popularized	by	Erlang,	now	in	Scala
Simple	and	high-level	abstractions	for	concurrency	and
parallelism
Objects	are	Actors	each	with	their	own	state	which	is	never
shared
Communication	happens	through	messages
Very	lightweight	event-driven	processes	(approximately	2.7
million	actors	per	GB	RAM	[Akka])
THE	ACTOR	MODEL	-2
Easier	to	deal	with	humans	than	with	threads
Like	humans,	Actors	communicate	via	messages
No	state	sharing,	communicate	via	immutable	messages
IMPLEMENTATIONS
PRODUCER	CONSUMER	PROBLEM
Demo	with	JRuby	+	Locks
Demo	with	JRuby	+	Celluloid
PRODUCER	CONSUMER
with	locks
HTTPS://GIST.GITHUB.COM/ROCKY-
JAISWAL/5847810
PRODUCER	CONSUMER
with	actors
HTTPS://GIST.GITHUB.COM/ROCKY-
JAISWAL/5847814
SUMMARY
Concurrency	is	the	need	of	the	hour
MRI	is	thread	safe	by	default	due	to	GIL	/	GVL
JRuby	gives	you	real	concurrency	(RBX	as	well)
With	power	comes	responsibility
Don't	worry,	concurrency	can	be	easy	if	you	follow	the
ground	rules
If	you	want	to	write	concurrent	code	yourself,	use
Actors
*	I	did	not	cover	STM	(provided	by	Clojure)
THANK	YOU!
QUESTIONS
#A	lot	of	this	content	has	been	taken	from	blogs,	wikis	and	books.	I	do	not	claim	it	is	my
own	and	I	wholeheartedly	thank	everyone	who	helped	me	with	this	presentation.

Contenu connexe

Tendances (8)

Rubyhosting
RubyhostingRubyhosting
Rubyhosting
 
JRuby - Everything in a single process
JRuby - Everything in a single processJRuby - Everything in a single process
JRuby - Everything in a single process
 
AWS Lambdas are cool - Cheminfo Stories Day 1
AWS Lambdas are cool - Cheminfo Stories Day 1AWS Lambdas are cool - Cheminfo Stories Day 1
AWS Lambdas are cool - Cheminfo Stories Day 1
 
Introduction To Rails
Introduction To RailsIntroduction To Rails
Introduction To Rails
 
My S Q L Replication Getting The Most From Slaves
My S Q L  Replication  Getting  The  Most  From  SlavesMy S Q L  Replication  Getting  The  Most  From  Slaves
My S Q L Replication Getting The Most From Slaves
 
kranonit S06E01 Игорь Цинько: High load
kranonit S06E01 Игорь Цинько: High loadkranonit S06E01 Игорь Цинько: High load
kranonit S06E01 Игорь Цинько: High load
 
Ruby on Rails : First Mile
Ruby on Rails : First MileRuby on Rails : First Mile
Ruby on Rails : First Mile
 
Scaling a Web Service
Scaling a Web ServiceScaling a Web Service
Scaling a Web Service
 

En vedette

Lightning Talk - Contribute to Open Source
Lightning Talk - Contribute to Open SourceLightning Talk - Contribute to Open Source
Lightning Talk - Contribute to Open Source
Sidu Ponnappa
 
Creating actionable marketo reports july, 2013
Creating actionable marketo reports   july, 2013Creating actionable marketo reports   july, 2013
Creating actionable marketo reports july, 2013
Inga Romanoff
 
Larry's Free Culture
Larry's Free CultureLarry's Free Culture
Larry's Free Culture
Kapil Mohan
 

En vedette (20)

What lies beneath the beautiful code?
What lies beneath the beautiful code?What lies beneath the beautiful code?
What lies beneath the beautiful code?
 
Testing smells
Testing smellsTesting smells
Testing smells
 
Lightning Talk - Contribute to Open Source
Lightning Talk - Contribute to Open SourceLightning Talk - Contribute to Open Source
Lightning Talk - Contribute to Open Source
 
Everything ruby
Everything rubyEverything ruby
Everything ruby
 
Ruby Internals
Ruby InternalsRuby Internals
Ruby Internals
 
Aspen ideas Festival Talk on Gov20
Aspen ideas Festival Talk on Gov20Aspen ideas Festival Talk on Gov20
Aspen ideas Festival Talk on Gov20
 
clearScienceStrataRx2012
clearScienceStrataRx2012clearScienceStrataRx2012
clearScienceStrataRx2012
 
Awakening India - Jago Party
Awakening India - Jago PartyAwakening India - Jago Party
Awakening India - Jago Party
 
Open Data: From the Information Age to the Action Age (Keynote File)
Open Data: From the Information Age to the Action Age (Keynote File)Open Data: From the Information Age to the Action Age (Keynote File)
Open Data: From the Information Age to the Action Age (Keynote File)
 
Creating actionable marketo reports july, 2013
Creating actionable marketo reports   july, 2013Creating actionable marketo reports   july, 2013
Creating actionable marketo reports july, 2013
 
Larry's Free Culture
Larry's Free CultureLarry's Free Culture
Larry's Free Culture
 
Parzania Movie Preview
Parzania Movie PreviewParzania Movie Preview
Parzania Movie Preview
 
What we can take for granted in online communities
What we can take for granted in online communitiesWhat we can take for granted in online communities
What we can take for granted in online communities
 
BodyTrack: Open Source Tools for Health Empowerment through Self-Tracking
BodyTrack: Open Source Tools for Health Empowerment through Self-Tracking BodyTrack: Open Source Tools for Health Empowerment through Self-Tracking
BodyTrack: Open Source Tools for Health Empowerment through Self-Tracking
 
A New Business World Within A Blockchain
A New Business World Within A BlockchainA New Business World Within A Blockchain
A New Business World Within A Blockchain
 
Pinterest for Business 101
Pinterest for Business 101Pinterest for Business 101
Pinterest for Business 101
 
Visual Conversations on Urban Futures - DRS 2016
Visual Conversations on Urban Futures - DRS 2016Visual Conversations on Urban Futures - DRS 2016
Visual Conversations on Urban Futures - DRS 2016
 
A GeoSocial Intelligence Framework for Studying & Promoting Resilience to Sea...
A GeoSocial Intelligence Framework for Studying & Promoting Resilience to Sea...A GeoSocial Intelligence Framework for Studying & Promoting Resilience to Sea...
A GeoSocial Intelligence Framework for Studying & Promoting Resilience to Sea...
 
Cio Exchange08
Cio Exchange08Cio Exchange08
Cio Exchange08
 
Government 2.0
Government 2.0Government 2.0
Government 2.0
 

Similaire à Concurrency & Ruby

Similaire à Concurrency & Ruby (20)

JRuby and Google App Engine
JRuby and Google App EngineJRuby and Google App Engine
JRuby and Google App Engine
 
Exploring Ruby on Rails and PostgreSQL
Exploring Ruby on Rails and PostgreSQLExploring Ruby on Rails and PostgreSQL
Exploring Ruby on Rails and PostgreSQL
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
Parallel js
Parallel jsParallel js
Parallel js
 
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
 
Message Queues in Ruby - An Overview
Message Queues in Ruby - An OverviewMessage Queues in Ruby - An Overview
Message Queues in Ruby - An Overview
 
re7olabini
re7olabinire7olabini
re7olabini
 
Day 8 - jRuby
Day 8 - jRubyDay 8 - jRuby
Day 8 - jRuby
 
NodeJS or Apache: Unveiling the Differences in Performance, Use Cases, and Se...
NodeJS or Apache: Unveiling the Differences in Performance, Use Cases, and Se...NodeJS or Apache: Unveiling the Differences in Performance, Use Cases, and Se...
NodeJS or Apache: Unveiling the Differences in Performance, Use Cases, and Se...
 
What's the "right" PHP Framework?
What's the "right" PHP Framework?What's the "right" PHP Framework?
What's the "right" PHP Framework?
 
Feels Like Ruby - Ruby Kaigi 2010
Feels Like Ruby - Ruby Kaigi 2010Feels Like Ruby - Ruby Kaigi 2010
Feels Like Ruby - Ruby Kaigi 2010
 
Ruby/Rails Performance Tips
Ruby/Rails Performance TipsRuby/Rails Performance Tips
Ruby/Rails Performance Tips
 
Node.JS Expreee.JS scale webapp on Google cloud
Node.JS Expreee.JS scale webapp on Google cloudNode.JS Expreee.JS scale webapp on Google cloud
Node.JS Expreee.JS scale webapp on Google cloud
 
performance_tuning.pdf
performance_tuning.pdfperformance_tuning.pdf
performance_tuning.pdf
 
performance_tuning.pdf
performance_tuning.pdfperformance_tuning.pdf
performance_tuning.pdf
 
Gluecon 2014 - Bringing Node.js to the JVM
Gluecon 2014 - Bringing Node.js to the JVMGluecon 2014 - Bringing Node.js to the JVM
Gluecon 2014 - Bringing Node.js to the JVM
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
 
Languages used by web app development services remotestac x
Languages used by web app development services  remotestac xLanguages used by web app development services  remotestac x
Languages used by web app development services remotestac x
 
DiUS Computing Lca Rails Final
DiUS  Computing Lca Rails FinalDiUS  Computing Lca Rails Final
DiUS Computing Lca Rails Final
 
Rails Concept
Rails ConceptRails Concept
Rails Concept
 

Dernier

Dernier (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 

Concurrency & Ruby