Concurrency P1: What even is this concurrency thing?

10 Sep 2018

So you hear all these things about threads, concurrency, parallelism, asynchronous calls, you name it. It sounds fancy and perhaps a little bit scary. Not to worry though, I hope to make it all a bit clearer throughout this concurrency series.

Let’s dive right in and find out what concurrency actually is. Very generally, it is the ability of a program to do multiple things at once or have tasks run independently of one another. For example, a text processing program is displaying a GUI, waiting for input, backing up what you’ve written and perhaps checking for updates. There is no way it can do all of these tasks sequentially. The GUI would freeze every time it had to do a backup or checks for updates and nothing else would be interactive while the program is waiting for input from you. All in all a terrible experience. A program illustation

This is where concurrency comes in and each of these tasks get their own thread, which is responsible for it’s own specific task. A thread usually only has one specific purpose, for example, counting seconds on a stopwatch. This means another thread can listen for input to start or stop the stopwatch thread. In Java, this is what a thread looks like.

public class CounterThread extends Thread {
    int counter = 1;

    public void run() {
        while(true) {

    public static void main(String args[]) {
        (new CounterThread()).start();

This is just a simple thread that will increment a counter and go to sleep for one second, effectively counting seconds.

Now all this thread stuff sounds super useful and (hopefully) pretty easy. So what’s all the fuzz about? Well, it turns out that managing many of these threads can become a massive headache if they have to work with the same resource. Maybe you’ve tried working in a team on a presentation (back in the day where Google Docs wasn’t a thing). You and your friend open the same file and you spend an hour making the most amazing presentation ever and you save it. However, because your friend has the same file open but without your amazing changes and saves out of habit when they close the file, all of your amazing work is gone.

This is exactly what happens with threads using the same resource and it can become a giant mess of lost data, corruption and unexpected behavior.

So to utilize the concurrency benefit threads provide, we need rules, properties and algorithms to ensure all the threads play nice. These are the things we’ll be looking into over this series.

In the next blog post we’ll be looking at critical sections, which is a term for the block of code where a thread accesses a shared resource.