ivanursul

Software engineer

Concurrency structures written using core java

Motivation

The reason for writing this article is a lack of my understanding of Java concurrency. That’s why I decided to create a post with some structures, which I wrote by myself. For sure, you may agree or disagree with me, I encourage to post your thoughts in comments so we can discuss them there.

List of structures

Implemented:

Will implement them later:

Publish/Subscribe

What is Publish-Subscribe, in a nutshell? Obviously, there someone, who has something share something to others, and want to be sure, that everyone will receive this message.

The idea of following structure is to have a publish-subscribe mechanism, which will act asynchronously, without usage of high-level classes from java.util.concurrent package:

Code can be found here.

Let’s go over this code and try all the details:

Queue

Queue is something different from publish-subscribe way of sending messages - there’s a shared resource, queue, and each consumer attempts to read from it, and because of concurrency monitor, only one will manage to do that.

Code can be found here

What, if we would like to decide, who is going to consume this message? Let’s say, we have consumer groups and want to address some messages to some consumer groups? Here is a new version of QueueModel.

The output will look like this:

Message 1
group2
group2: Consumer4: Consuming message: Message{message='Message 1', consumerGroup='group2'}
Message 2
group2
group1: Consumer5: Skipping message, wrong group, message: Message{message='Message 2', consumerGroup='group2'}
group1: Consumer6: Skipping message, wrong group, message: Message{message='Message 2', consumerGroup='group2'}
group1: Consumer7: Skipping message, wrong group, message: Message{message='Message 2', consumerGroup='group2'}
group1: Consumer8: Skipping message, wrong group, message: Message{message='Message 2', consumerGroup='group2'}
group1: Consumer9: Skipping message, wrong group, message: Message{message='Message 2', consumerGroup='group2'}
group1: Consumer0: Skipping message, wrong group, message: Message{message='Message 2', consumerGroup='group2'}
group2: Consumer1: Consuming message: Message{message='Message 2', consumerGroup='group2'}

This approach is doing his work, however, there’s a problem: I don’t like the idea of receiving a message if you are initially a wrong recipient. It’s the same if you will get a call from post service with a package for your neighbor. That’s why here is a new version of QueueModel. The difference is straighforward - now each consumer group has it’s own queue, so you don’t need to mix things up.