Queues are common in many applications, ranging from printing jobs to background workers in web applications.

Let’s say we were programming a simple Ruby interface for a printer that can accept printing jobs from various computers across a network. We want to make sure we print each document in the order in which they were received.

This code uses our Ruby implementation of the Queue class from earlier:

​  ​ class ​ PrintManager
​  
​  ​ def ​ ​ initialize ​
​  @queue = Queue.​ new ​
​  ​ end ​
​  
​  ​ def ​ ​ queue_print_job ​(document)
​  @queue.​ enqueue ​(document)
​  ​ end ​
​  
​  ​ def ​ ​ run ​
​  ​ # Each time this loop runs, we read the document ​
​  ​ # at the front of the queue: ​
​  ​ while ​ @queue.​ read ​
​  ​ # We dequeue the document and print it: ​
​  print(@queue.​ dequeue ​)
​  ​ end ​
​  ​ end ​
​  
​  ​ private ​
​  
​  ​ def ​ ​ print ​(document)
​  ​ # Code to run the actual printer goes here. ​
​  ​ # For demo purposes, we'll print to the terminal: ​
​  puts document
​  ​ end ​
​  
​  ​ end ​

We can then utilize this class as follows:

​  print_manager = PrintManager.​ new ​
​  print_manager.​ queue_print_job ​(​ "First Document" ​)
​  print_manager.​ queue_print_job ​(​ "Second Document" ​)
​  print_manager.​ queue_print_job ​(​ "Third Document" ​)
​  print_manager.​ run ​

Each time we call queue_print_job , we add the “document” (represented by a string, in this example) to the queue:

​  ​ def ​ ​ queue_print_job ​(document)
​  @queue.​ enqueue ​(document)
​  ​ end ​

When we call run , we print each document by processing them in the order in which they were received:

​  ​ def ​ ​ run ​
​  ​ while ​ @queue.​ read ​
​  print(@queue.​ dequeue ​)
​  ​ end ​
​  ​ end ​

Note how we dequeue each document as we print it.

When we run the previous code, the program will output the three documents in the same order in which they were received:

​  First Document
​  Second Document
​  Third Document

While this example is simplified and abstracts away some of the nitty-gritty details that a real live printing system may have to deal with, the fundamental use of a queue for such an application is very real and serves as the foundation for building such a system.

Queues are also the perfect tool for handling asynchronous requests—they ensure that the requests are processed in the order in which they were received. They are also commonly used to model real-world scenarios where events need to occur in a certain order, such as airplanes waiting for takeoff and patients waiting for their doctor.