Processes & Threads

Most operating systems support concurrent executions and programming languages allow you to develop programs which allow you to utilise this awesome super-power. Except Python, which suffers from a disease called Global Interpreter Lock

Processes are programs which typically run independent to each other. Within these processes, we have Threads, which usually work within the same leaps and bounds of a process accessing variables colocated, that is to say written in the same code.

Java supports threads since JDK 1. To define a thread, you also define what it has to do, often referred as a task. This can either be a task which does not return anything, called a Runnable, or something which does some processing, and returns something, a Callable.

Define a Task

Here, we define a simple task which says hello.

Runnable greetingTask = () -> {
    System.out.println("Hello from " + Thread.currentThread().getName());
};

greetingTask.run();

The output is going to look something like this

Hello from main

Create a Thread

Lets create a separate thread to run this task on. Observe the thread creation syntax below:

Runnable greetingTask = () -> {
    System.out.println("Hello from " + Thread.currentThread().getName());
};

Thread thread = new Thread(greetingTask);
thread.start();

And you should see something like:

Hello from thread-0

So that’s all we need for Concurrency, right?

Well consider doing a real task. (See that’s why I hate Dog extends Animal examples). Either way, lets say you were trying to make a pizza, and you assign different threads different tasks - makeDough, sprinkleCheese, bakePizza, and finally you expect to eatPizza.

You rely on order of execution and expect things to be executed sequentially.

Runnable makeDough = () -> {
    try {
        System.out.println("Making Dough");
        TimeUnit.SECONDS.sleep(4);
        System.out.println("Dough is Ready!");
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
};

Runnable sprinkleCheese = () -> {
    try {
        System.out.println("Getting some Mozarella");
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Sprinkling some Mozarella");
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
};

Runnable bakePizza = () -> {
    try {
        System.out.println("Baking Pizza");
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Pizza Baked");
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
};

Runnable eatPizza = () -> {
    try {
        System.out.println("Eating Pizza");
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Yummy Yummy In My Tummy");
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
};

Thread thread1 = new Thread(makeDough);
Thread thread2 = new Thread(sprinkleCheese);
Thread thread3 = new Thread(bakePizza);
Thread thread4 = new Thread(eatPizza);
thread1.start();
thread2.start();
thread3.start();
thread4.start();

What you’d expect:

Making Dough
Dough is Ready!
Getting some Mozarella
Sprinkling some Mozarella
Baking Pizza
Pizza Baked
Eating Pizza
Yummy Yummy In My Tummy

What you might end up seeing:

Making Dough
Getting some Mozarella
Baking Pizza
Eating Pizza
Sprinkling some Mozarella
Pizza Baked
Yummy Yummy In My Tummy
Dough is Ready!

If you run this code over and over, you’ll see really weird results. Since there’s no way of knowing which statement would be executed first, it was a pain to build programs which used concurrency. Java introduced Concurrency API with Java 5 back in 2004, about the same time when this lad launched Facebook from his Harvard Dorm Room.

This blog post is part of the Advanced Java Series. Continue here with the Concurrency API.

Feeling generous ? Help me write more blogs like this :)


Feeling even more generous ?

$20 can feed a poor child for a whole year. Akshaya Patra (Aak-sh-ayah pa-tra) is the world’s largest NGO school meal program, providing hot, nutritious school lunches to over 1.8 million children in 19,257 schools, across India every day. Your 20$ makes all the difference.