Slide 1

Slide 1 text

@josevalim / Plataformatec Concurrency Ruby in

Slide 2

Slide 2 text

About me

Slide 3

Slide 3 text

•Started with Ruby in 2006 About me

Slide 4

Slide 4 text

•Started with Ruby in 2006 •Open Source Contributor About me

Slide 5

Slide 5 text

•Started with Ruby in 2006 •Open Source Contributor •Joined Rails Core in 2010 About me

Slide 6

Slide 6 text

•Started with Ruby in 2006 •Open Source Contributor •Joined Rails Core in 2010 •Author of elixir-lang.org About me

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

Topics

Slide 9

Slide 9 text

•Why concurrency? Topics

Slide 10

Slide 10 text

•Why concurrency? •The problem today Topics

Slide 11

Slide 11 text

•Why concurrency? •The problem today •Learning from others Topics

Slide 12

Slide 12 text

Why concurrency?

Slide 13

Slide 13 text

Server Server Server Server

Slide 14

Slide 14 text

50 cores $2600

Slide 15

Slide 15 text

It is no longer about the future, it is about now

Slide 16

Slide 16 text

Server

Slide 17

Slide 17 text

In Ruby, we talk about threads

Slide 18

Slide 18 text

We need our applications to be thread-safe

Slide 19

Slide 19 text

The problem

Slide 20

Slide 20 text

class User def self.current_user=(user) @@current_user = user end def self.current_user @@current_user end end

Slide 21

Slide 21 text

post "/do_something" do User.current_user = user_from_request # some work Mailer.deliver_to( User.current_user) end

Slide 22

Slide 22 text

1. Assign current_user 2. Do some work 3. Get current_user to send an e-mail

Slide 23

Slide 23 text

thread 1 current_ user thread 2

Slide 24

Slide 24 text

thread 1 current_ user thread 2 jose

Slide 25

Slide 25 text

thread 1 current_ user thread 2 jose jose

Slide 26

Slide 26 text

thread 1 current_ user thread 2 jose jose jose

Slide 27

Slide 27 text

thread 1 current_ user thread 2 jose jose jose jose

Slide 28

Slide 28 text

thread 1 current_ user thread 2 jose jose matz jose jose

Slide 29

Slide 29 text

thread 1 current_ user thread 2 jose jose matz matz jose jose

Slide 30

Slide 30 text

thread 1 current_ user thread 2 jose jose matz matz jose jose jose

Slide 31

Slide 31 text

thread 1 current_ user thread 2 jose jose matz matz jose jose jose jose

Slide 32

Slide 32 text

thread 1 current_ user thread 2 jose jose matz matz jose jose jose jose jose

Slide 33

Slide 33 text

thread 1 current_ user thread 2 jose jose matz matz jose jose jose jose jose jose

Slide 34

Slide 34 text

thread 1 current_ user thread 2 jose jose matz matz jose jose jose jose jose jose

Slide 35

Slide 35 text

User.current_user is shared mutable state (global)

Slide 36

Slide 36 text

ActionMailer::Base.from ActionController::Base.logger Devise.password_length SimpleForm.form_options

Slide 37

Slide 37 text

What is Ruby?

Slide 38

Slide 38 text

Ruby is a programming language with different implementations

Slide 39

Slide 39 text

Rails 2.2 threadsafe

Slide 40

Slide 40 text

Not really ...

Slide 41

Slide 41 text

Thread-safety means different things for different implementations

Slide 42

Slide 42 text

class ActionController::Base prepend_view_path( ActionView::Resolver.new("app/views") ) end

Slide 43

Slide 43 text

# It finds Rails templates and # caches them in between requests class ActionView::Resolver def initialize @cached = Hash.new { ... } end end

Slide 44

Slide 44 text

@cached[template] = File.read(template)

Slide 45

Slide 45 text

Thread-safe YARV Yes JRUBY No RBX 2.0 No Hashes

Slide 46

Slide 46 text

global virtual machine lock (YARV) @cached[template] = File.read(template) static VALUE env_aset(VALUE obj, VALUE nm, VALUE val) { ... hash.c

Slide 47

Slide 47 text

global virtual machine lock (YARV) @cached[template] = File.read(template) static VALUE env_aset(VALUE obj, VALUE nm, VALUE val) { ... hash.c

Slide 48

Slide 48 text

Without the GVL, other Ruby implementations may try to change the same Hash at the same time, corrupting it

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

Very low-level abstractions

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

Code maintainability

Slide 56

Slide 56 text

Code maintainability YARV performance

Slide 57

Slide 57 text

Code maintainability YARV performance Developer happiness

Slide 58

Slide 58 text

• Class definitions • Instance variables • Class variables • Data structures ...

Slide 59

Slide 59 text

We need to define proper semantics and provide better abstractions

Slide 60

Slide 60 text

Learning from others

Slide 61

Slide 61 text

Java

Slide 62

Slide 62 text

thread.rb Thread Mutex ConditionVariable Queue SizedQueue

Slide 63

Slide 63 text

java.util.concurrent ArrayBlockingQueue ConcurrentHashMap ConcurrentLinkedQueue ConcurrentSkipListMap ConcurrentSkipListSet CopyOnWriteArrayList CopyOnWriteArraySet CountDownLatch CyclicBarrier DelayQueue Exchanger FutureTask LinkedBlockingDeque LinkedBlockingQueue PriorityBlockingQueue PriorityQueue Semaphore SynchronousQueue

Slide 64

Slide 64 text

java.util.concurrent ArrayBlockingQueue ConcurrentHashMap ConcurrentLinkedQueue ConcurrentSkipListMap ConcurrentSkipListSet CopyOnWriteArrayList CopyOnWriteArraySet CountDownLatch CyclicBarrier DelayQueue Exchanger FutureTask LinkedBlockingDeque LinkedBlockingQueue PriorityBlockingQueue PriorityQueue Semaphore SynchronousQueue ETOOMANYCLASSES

Slide 65

Slide 65 text

Hashes

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

“There are heaps of non thread-safe usage of Hashes in Rails and the surrounding gems”

Slide 68

Slide 68 text

Using hashes as a cache is an extremely common pattern in Ruby

Slide 69

Slide 69 text

@cached[template] = File.read(template)

Slide 70

Slide 70 text

Thread-safe YARV Yes JRUBY No RBX 2.0 No Hashes

Slide 71

Slide 71 text

- @cached = {} + @cached = ConcurrentHash.new

Slide 72

Slide 72 text

- @cached = {} + @cached = ConcurrentHash.new

Slide 73

Slide 73 text

Ruby under a microscope “How hashes scale from one to one million elements”

Slide 74

Slide 74 text

One class to rule them all!

Slide 75

Slide 75 text

Proposal #1

Slide 76

Slide 76 text

1. add Hash#concurrent_read and Hash#concurrent_write Proposal #1

Slide 77

Slide 77 text

1. add Hash#concurrent_read and Hash#concurrent_write 2. allow implementations to have different default values Proposal #1

Slide 78

Slide 78 text

# YARV hash = Hash.new hash.concurrent_read #=> true hash.concurrent_write #=> true # JRUBY hash = Hash.new hash.concurrent_read #=> false hash.concurrent_write #=> false # RBX hash = Hash.new hash.concurrent_read #=> ? hash.concurrent_write #=> ?

Slide 79

Slide 79 text

# When you need thread safety # in any implementation: hash = Hash.new hash.concurrent_read! hash.concurrent_write!

Slide 80

Slide 80 text

AtomicReference

Slide 81

Slide 81 text

class User def name=(name) @name = name end def name @name end end user = User.new

Slide 82

Slide 82 text

10.times do Thread.new { user.name = "Hello #{rand}" } end Threadsafe?

Slide 83

Slide 83 text

Defining Updating YARV Yes Yes JRUBY Yes No RBX 2.0 ? ? Instance variables

Slide 84

Slide 84 text

class User def initialize @name = AtomicReference.new end def name @name.get end def name=(name) @name.set(name) end end

Slide 85

Slide 85 text

class User atomic_accessor :name end

Slide 86

Slide 86 text

class User def initialize # Provide a default # lazily calculated value @name = AtomicReference.new do expensive_calculation end end end

Slide 87

Slide 87 text

Defining Updating YARV Yes Yes JRUBY Yes No RBX 2.0 ? ? Instance variables

Slide 88

Slide 88 text

Proposal #2

Slide 89

Slide 89 text

1. updating instance variables are declared unsafe Proposal #2

Slide 90

Slide 90 text

1. updating instance variables are declared unsafe 2. any thread-safe Ruby code needs to treat them as such Proposal #2

Slide 91

Slide 91 text

Proposal #2

Slide 92

Slide 92 text

3. implementations like YARV can still provide safe semantics due to technical limitation Proposal #2

Slide 93

Slide 93 text

3. implementations like YARV can still provide safe semantics due to technical limitation 4. but code that relies on such behavior works by “accident” Proposal #2

Slide 94

Slide 94 text

Proposal #2

Slide 95

Slide 95 text

5. add AtomicReference to thread.rb Proposal #2

Slide 96

Slide 96 text

5. add AtomicReference to thread.rb Proposal #2 AtomicReference#new(&default) AtomicReference#set(value) AtomicReference#get()

Slide 97

Slide 97 text

AtomicReference #get_and_set(new) AtomicReference #compare_and_swap(old, new)

Slide 98

Slide 98 text

compare_and_swap is the first step required for implementing lock-free data structures

Slide 99

Slide 99 text

Go

Slide 100

Slide 100 text

Go shows us we can go a long way with simple (but powerful) abstractions and great education

Slide 101

Slide 101 text

“Do not communicate by sharing memory; instead, share memory by communicating”

Slide 102

Slide 102 text

is_done = false Thread.new { # do something expensive is_done = true # do something else } sleep(0.5) until is_done # a bit more work puts :DONE

Slide 103

Slide 103 text

Go made Channels and Goroutines first-class citizens of the language

Slide 104

Slide 104 text

done := make(chan bool, 1) go func() { // do something expensive done <- true // do something else }() <-done // a bit more work

Slide 105

Slide 105 text

queue = SizedQueue.new(1) Thread.new { # do something expensive queue << true # do something else } queue.pop # a bit more work puts :DONE

Slide 106

Slide 106 text

Ruby already has Queues! Let’s do more on top of it!

Slide 107

Slide 107 text

select { case <-ch: // a read from ch has occurred case <-done: // the done channel is done }

Slide 108

Slide 108 text

thread.rb Thread Mutex ConditionVariable Queue SizedQueue

Slide 109

Slide 109 text

But there is something more...

Slide 110

Slide 110 text

Erlang

Slide 111

Slide 111 text

Both Erlang and Go have lightweight concurrent primitives, scheduled by the language

Slide 112

Slide 112 text

How much does a thread cost in Ruby?

Slide 113

Slide 113 text

Erlang -> Processes Go -> Goroutines Ruby -> ?

Slide 114

Slide 114 text

Proposal #3

Slide 115

Slide 115 text

1. Let’s make our Queue more powerful (with sizes and de-multiplexing) Proposal #3

Slide 116

Slide 116 text

Proposal #4

Slide 117

Slide 117 text

1. Provide lightweight, concurrent scheduled primitives Proposal #4

Slide 118

Slide 118 text

Finally, what about the Actor model?

Slide 119

Slide 119 text

github.com/celluloid

Slide 120

Slide 120 text

The Actor model is about building systems. Ruby should make it easier for them to flourish.

Slide 121

Slide 121 text

Conclusion

Slide 122

Slide 122 text

The different semantics existing in different implementations makes concurrency in Ruby harder

Slide 123

Slide 123 text

We are also not used to think about concurrency. We need more education on how to “think concurrently”

Slide 124

Slide 124 text

We need...

Slide 125

Slide 125 text

We need... • well-defined semantics

Slide 126

Slide 126 text

We need... • well-defined semantics • a thread-safe stdlib (example: Hash#concurrent_write!)

Slide 127

Slide 127 text

We need... • well-defined semantics • a thread-safe stdlib (example: Hash#concurrent_write!) • high-level abstractions & education (example: atomic, queues)

Slide 128

Slide 128 text

My goal is not to propose final solutions but instigate discussion. I hope I have fulfilled it!

Slide 129

Slide 129 text

Thank you! @josevalim / Plataformatec