An Introduction to Celluloid, Part II

Share this article

This is the second article in the three-part series. If you missed the first one, you can find it here

Celluloid has a ton more awesome tools to make concurrent programming incredibly easy in Ruby.

Let’s take a look at them.

Futures

There are times when we don’t just want to discard the return value of a method we’ve called on an actor; instead, we might want to use it somewhere else. For that, Celluloid provides futures. The best way to learn about them is to see them in action.

We’ll write a small script that computes the SHA1 checksum of an array of files, then outputs them to the console.

Without further ado, here it is:

[gist id=”3169115″]

First of all, consider the checksum method. It is quite straightforward, we use the Digest::SHA1 to compute the checksum of the contents of a file that the actor is given.

Look at the files.each loop. This is where it gets interesting.

First, we create the actor and assign it a file. Then, instead of just calling the checksum method, we call it using a future. By doing this, a Celluloid::Future object is immediately returned, instead of blocking.

Then, we take this future object and pass it on to the output method inside the actor.
Inside the output method, the value of the checksum is needed! So, it is attained from the future object’s value method, which blocks until a value is available. That solves the problem!

You might be thinking, “hey, this does pretty much the same thing as the last example!” However, in the last example, in order to do the file related operations asynchronously, we dumped everything into a single method. With futures, we are able to cleanly seperate our code.

Also, there are use cases where it is only possible to use futures. For example, if one is writing a library, the result of the checksum function must be a future since the user of the library should be able to add in their own code.

Making Any Block Concurrent

There is a very cool use for futures, namely, they allow us to push block of code to another thread incredibly easily.

Check it out:

[gist id=”3169318″]

We use Celluloid::Future to push a block into its own thread. Celluloid manages everything about that thread, whose return value we can use later on (using the future’s return value, of course). So, this little part of Celluloid can be plugged into literally any application and once mastered, can be incredibly useful.

Use it wisely!

Catching Errors – Supervisors

To see how error handling works in Celluloid, we’re going to build a simple tool that gets the HTML of various websites.

Here it is, with the stuff we’ve learned so far:

[gist id=”3169206″]

If everything goes well, the markup is putsd.

But, what if things start going wrong? We’re not really doing much about that.

For that purpose, Celluloid provides a mechanism known as a supervisor. Here it is in action:

[gist id=”3169282″]

There’s several new concepts here, so pay close attention.

First of all, the MarkupPutter class is left untouched. In other words, the implementation of the business logic is left unchanged!

Now, we call the supervise method on the MarkupPutter class. This does three things, first, it creates (and puts into motion) an actor that is an instance of MarkupPutter. Secondly, it returns a supervisor object, which can do some interesting things. Finally, it takes its first argument (which is “mp”), and puts an entry of that name in the registry.

The Celluloid registry is a bit like a phonebook – the actors that are in there can be accessed by name. So, on the next line, we use the Celluloid registry to look up :mp.

The code after that is quite straightforward – simply using a future to output the markup.

With two lines of code added, Celluloid automatically takes care of restarting and keeping track of actors when they crash!

In case one of the actors hits some kind of exception (e.g. the website does not respond to the request and the request times out), the actor is immediately restarted by the Celluloid core. If you’ve written this kind of threading code the old fashioned way, you know that this is a very finicky and difficult process, but it is handled entirely by Celluloid for us!

Communication Between Actors

In nearly all applications, actors will not be working in isolated environments – they will be communicating with other actors.

Just to explain how communication between actors works in Celluloid, we’ll write three actors to print out “Hello, world!” when run correctly. Check it out:

[gist id=”3169390″]

We start out by defining three actors, which each say a part of the “Hello, world!n” message. HelloSpaceActor uses the registry to look up the WorldActor instance and calls say_msg on it, then, WorldActor does the same for NewlineActor.

So, long story short, the actor communication is done with the actor Registry, where we are able to give the actors names.

As we know, another way to make actors work together is futures – have futures passed around between actors in order to get return values.

Blocking Calls Inside Actors

If you have experience with EventMachine, you know that you can’t mix EventMachine with any other library for IO – the library needs to be EventMachine compatible.

As such, you aren’t able to utilize the full power of the Ruby community. Instead, you are stuck with the far smaller EventMachine community.
With Celluloid, this isn’t the case!

Since the actors are all in their own threads, it is perfectly okay for method calls inside actors to block, since it only blocks that one actor!

But, beware. Do not make infinitely blocking calls in actors (such as listening on a socket) – this leads to all messages going to that actor to beome paused, which is bad!

Pooling

If you have read up a bit about how web servers operate, you know how important thread pools are. Pools in Celluloid are awesome; they are completely transparent. I think they are probably my favorite feature of Celluloid (with so much cool stuff, its hard to choose!).

We’ll write a simple example to demonstrate how amazing they are:

[gist id=”3169620″]

First, we define the PrimeWorker class. The “Worker” in the name signifies that it is to be used with a pool – threads that are part of thread pools are usually called workers.

The function of the prime method in PrimeWorker is to print a number if it is prime (this uses the ‘mathn’ module introduced in 1.9 – you can write your own prime number checker if you like).

The interesting part is when we introduce the pool by calling the pool method on PrimeWorker.

The “pool” object has all the methods of PrimeWorker, but, it actually creates as many instances of PrimeWorker as the processor has cores. Therefore, if you have a quad core processor, that would create four actors. When methods are called on “pool”, Celluloid decides which actor out of the pool to invoke.

Following that, we have a map over a large range, in which we call prime (remember, it is called asynchronously because of the bang) on pool. This automatically distributes the workload over your processors!

Wow. It took maybe four or five lines of code extra to acheive complete concurrency. That’s amazing.

At the end of the program, there is a sleep call. There is a good reason for this. Since we are calling prime asynchronously, the main thread (which is the Ruby thread) exits when it is done telling all the actors “hey, remember to print out this prime”. However, the actors aren’t done actually printing the primes by the time the main thread exits, so the output never reaches the terminal.

But, the sleep command keeps the main thread alive for long enough so that all the output comes out correctly. Also notice that since we are calling prime asynchronously, there is no gurantee of the order of the primes that are outputted.

Wrapping It Up

I hope you enjoyed the article, and that you’re as excited about Celluloid as I am.

So far, we’ve discussed how to use the various parts of Celluloid are to be used seperately with small examples.

In Part 3, we’ll cover how all of this ties together, create some more complex programs, and cover more features, such as Linking.

Do ask any questions you have in the comments section below :)

Dhaivat PandyaDhaivat Pandya
View Author

I'm a developer, math enthusiast and student.

celluloid
Share this article
Read Next
Automating Vultr Cloud Infrastructure with Terraform
Automating Vultr Cloud Infrastructure with Terraform
Vultr
Advanced Web Deployment With Plesk on Vultr
Advanced Web Deployment With Plesk on Vultr
Vultr
Building A 300 Channel Video Encoding Server
Building A 300 Channel Video Encoding Server
John O’Neill
Five Ways to Lazy Load Images for Better Website Performance
Five Ways to Lazy Load Images for Better Website Performance
Maria Antonietta Perna
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Vultr
Create a Toggle Switch in React as a Reusable Component
Create a Toggle Switch in React as a Reusable Component
Praveen KumarMichael Wanyoike
Comparing Docker and Podman: A Guide to Container Management Tools
Comparing Docker and Podman: A Guide to Container Management Tools
Vultr
How to Deploy Flask Applications on Vultr
How to Deploy Flask Applications on Vultr
Vultr
A Comprehensive Guide to Understanding TypeScript Record Type
A Comprehensive Guide to Understanding TypeScript Record Type
Emmanuel Onyeyaforo
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
SitePoint Sponsors
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
SitePoint Sponsors
Momento Migrates Object Cache as a Service to Ampere Altra
Momento Migrates Object Cache as a Service to Ampere Altra
Dave Neary
Dev Hackathon: Reusable Creativity on Wix Studio
Dev Hackathon: Reusable Creativity on Wix Studio
SitePoint Sponsors
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
SitePoint Sponsors
How to Build Lightning Fast Surveys with Next.js and SurveyJS
How to Build Lightning Fast Surveys with Next.js and SurveyJS
Gavin Henderson
45 Visual Studio Code Shortcuts for Boosting Your Productivity
45 Visual Studio Code Shortcuts for Boosting Your Productivity
Shahed Nasser
Google Cloud Is the New Way to the Cloud
Google Cloud Is the New Way to the Cloud
SitePoint Sponsors
Understanding Vultr Content Delivery Networks (CDNs)
Understanding Vultr Content Delivery Networks (CDNs)
Vultr
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
SitePoint Sponsors
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain Zaidi
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form