Sitemap
Pawara Gunawardena

Pawara Gunawardena

Department of Computer Science and Engineering, Faculty of Engineering, University of Moratuwa, Sri Lanka.

Priority Queue Design Pattern

5 min readSep 30, 2026

--

The priority queue design pattern provides the capability to manage and process messages or related tasks based on their priority.

Press enter or click to view image in full size

The producer application assigns a priority value when producing a message, and the consumer application receives messages based on the priority order.

  • It handles higher-priority, urgent messages or tasks before lower-priority messages or tasks.
  • The message queue provides messages according to the priority, rather than in First-In, First-Out (FIFO) order.

Priority Queue Pattern

The priority queue pattern can be implemented using different approaches.

  • Single Queue
Press enter or click to view image in full size
  • Multiple Queues — Single Consumer Pool
Press enter or click to view image in full size
  • Multiple Queues — Multiple Consumer Pools
Press enter or click to view image in full size

Implementation

There are different types of message queues available. Below implementation uses the RabbitMQ which is an open source message broker.

Below explains the implementation of the Producer application which is a C++ application, and the implementation of the Consumer application which is a Java application.

This previous article describes implementation of a similar producer consumer application along with installation setup of dependencies.

Producer Application

For a RabbitMQ producer client libraries, RabbitMQ documentation explains multiple clients and this article uses the AMQP-CPP library.

Installation steps are explaining under the how to install section of the library project.

Below implementation has verified in a Linux Ubuntu environment with C++ 17 and verified with CMake based compile steps. Since this example depends on the TCP module it need to use the respective flags of the cmake command.

mkdir build
cd build
cmake .. -DAMQP-CPP_BUILD_SHARED=ON -DAMQP-CPP_LINUX_TCP=ON
cmake --build . --target install

MessageQueueTcpHandler implements the AMQP::TcpHandler pure virtual class interface.

#pragma once

#include <amqpcpp.h>
#include <amqpcpp/linux_tcp.h>

class MessageQueueTcpHandler : public AMQP::TcpHandler
{
virtual void onAttached(AMQP::TcpConnection *connection) override;
virtual void onConnected(AMQP::TcpConnection *connection) override;
virtual bool onSecured(AMQP::TcpConnection *connection, const SSL *ssl) override;
virtual void onReady(AMQP::TcpConnection *connection) override;
virtual void onError(AMQP::TcpConnection *connection, const char *message) override;
virtual void onClosed(AMQP::TcpConnection *connection) override;
virtual void onLost(AMQP::TcpConnection *connection) override;
virtual void onDetached(AMQP::TcpConnection *connection) override;
virtual void monitor(AMQP::TcpConnection *connection, int fd, int flags) override;
};
#include "MessageQueueTcpHandler.h"

void MessageQueueTcpHandler::onAttached(AMQP::TcpConnection *connection)
{

}

void MessageQueueTcpHandler::onConnected(AMQP::TcpConnection *connection)
{

}

bool MessageQueueTcpHandler::onSecured(AMQP::TcpConnection *connection, const SSL *ssl)
{
return true;
}

void MessageQueueTcpHandler::onReady(AMQP::TcpConnection *connection)
{

}

void MessageQueueTcpHandler::onError(AMQP::TcpConnection *connection, const char *message)
{

}

void MessageQueueTcpHandler::onClosed(AMQP::TcpConnection *connection)
{

}

void MessageQueueTcpHandler::onLost(AMQP::TcpConnection *connection)
{

}

void MessageQueueTcpHandler::onDetached(AMQP::TcpConnection *connection)
{

}

void MessageQueueTcpHandler::monitor(AMQP::TcpConnection *connection, int fd, int flags)
{

}

Producer application publish messages to the queue named demo_priority_queue. For the demonstration, within the implementation it uses the default authentication literal values.

Get Pawara Gunawardena’s stories in your inbox

Join Medium for free to get updates from this writer.

ProducerApplication.cpp produces to the demo_priority_queue.

#include <iostream>
#include <thread>
#include <ctime>
#include <amqpcpp.h>
#include <boost/asio/io_service.hpp>
#include <amqpcpp/libboostasio.h>
#include "MessageQueueTcpHandler.h"

const std::string QUEUE = "demo_priority_queue";
const std::string DEFAULT_EXCHANGE = "";
const std::string ROUTING_KEY = "demo_priority_queue";

int getIdleMilliseconds()
{
int idleMilliseconds = (10 + std::rand() % 3) * 100;
return idleMilliseconds;
}

std::string readData(const std::string& appId)
{
time_t timestamp;
time(&timestamp);
std::string data = "["+appId+"] "+ctime(&timestamp);
return data;
}

void publishToDefaultExchange(AMQP::TcpChannel& channel, const std::string& appId)
{
while(channel.usable())
{
const std::string data = readData(appId);

int priority = std::rand() % 11;

AMQP::Envelope envelope(data.c_str(), data.length());
envelope.setPriority(priority);

std::cout<<"Producer application publish priority " << priority << " - data " << data << std::endl;

channel.publish(DEFAULT_EXCHANGE, ROUTING_KEY, envelope);
std::this_thread::sleep_for(std::chrono::milliseconds(getIdleMilliseconds()));
}
}

int main(int argc, char *argv[])
{
std::cout<< std::endl;
std::srand(static_cast<unsigned int>(std::time(nullptr)));

boost::asio::io_service service(4);
AMQP::LibBoostAsioHandler handler(service);
AMQP::TcpConnection connection(&handler, AMQP::Address("amqp://<username>:<password>@localhost/"));
AMQP::TcpChannel channel(&connection);

AMQP::QueueCallback callback = [&](const std::string &name, int msgcount, int consumercount)
{
publishToDefaultExchange(channel, argv[1]);
};

AMQP::Table arguments;
arguments["x-max-priority"] = 10;

channel.declareQueue(QUEUE, AMQP::durable, arguments).onSuccess(callback);
return service.run();
}

To compile the program using g++, it needs amqpcpp, pthread and dl libraries.

g++ -g -Wall  ProducerApplication.cpp MessageQueueTcpHandler.cpp MessageQueueTcpHandler.h -o producer -lamqpcpp -lpthread -ldl

Executing the executable file will produce messages to the queue sample_priority_queue.

./producer producer_app

Consumer Application

For the Consumer Application, RabbitMQ documentation explains multiple clients and this article uses the Spring for RabbitMQ and the below implementation has verified in a Linux Ubuntu environment with Java 17.

Visit Spring Initializr and configure the project details.

Press enter or click to view image in full size

Dependencies:

  • Lombok
  • Spring for RabbitMQ

Update resources/application.properties

spring.application.name=consumer
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=<username>
spring.rabbitmq.password=<password>

rabbitmq.queue.name=demo_priority_queue
rabbitmq.exchange.name=
rabbitmq.routing.key=demo_priority_queue

MessageQueueConfig defines the configs of the message queue.

package com.demo.consumer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MessageQueueConfig {
@Value("${rabbitmq.queue.name}")
private String queue;

@Value("${rabbitmq.exchange.name}")
private String exchange;

@Value("${rabbitmq.routing.key}")
private String routingKey;

@Bean
public Queue priorityQueue() {
return QueueBuilder.durable(queue)
.withArgument("x-max-priority", 10)
.build();
}

@Bean
public DirectExchange exchange() {
return new DirectExchange(exchange);
}

@Bean
public Binding binding() {
return BindingBuilder
.bind(priorityQueue())
.to(exchange())
.with(routingKey);
}
}

MessageQueueConsumer consumes messages from the queue demo_priority_queue.

package com.demo.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.amqp.core.Message;

@Service
public class MessageQueueConsumer {
public static final Logger LOGGER = LoggerFactory.getLogger(MessageQueueConsumer.class);

@Value("${app.id}")
private String appId;

@RabbitListener(queues = {"${rabbitmq.queue.name}"})
public void consumer(Message message) throws InterruptedException {
int priority = message.getMessageProperties().getPriority();
LOGGER.info(String.format("Consumer application [%s] received priority %d - data %s", appId, priority, new String(message.getBody())));
}
}

ConsumerApplication defines the main method.

package com.demo.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumerApplication {

public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}

Once started the consumer application, it will consume messages from the queue demo_priority_queue.

gradle bootRun --args='--app.id=consumer_app'

Producer Application and Consumer Application Execution

Execution of the Producer Application and publishing data to the message queue.

Press enter or click to view image in full size

Execution of the Consumer Application and consuming data from the message queue.

Press enter or click to view image in full size

--

--

Pawara Gunawardena
Pawara Gunawardena

Written by Pawara Gunawardena

Department of Computer Science and Engineering, Faculty of Engineering, University of Moratuwa, Sri Lanka.