Java Thread Programming (Part 1)

What Is a Thread?

We write code in a file line by line, and then it gets executed. To be able to execute a piece of code requires an execution environment. In Java, a thread is an execution environment. If a program has only one execution environment, then we call this program a single-threaded program.

Interestingly, in Java, we can create a lot of threads to run different parts of the code of a program executing independently. And when we have achieved that, we call it a multi-threaded program.

Why the Cool Kids Use Event Loops

When I was working in software development back in the 1990s, nearly all the software libraries that I worked on made use of event loops. This was because at the time most hardware had just one single CPU. Back in the day, I remember the excitement when threads were introduced into our development framework. It was revolutionary that we could now run two things at once, or rather appear to run two things at once, since a lot of the hardware at that time still only had a single core, and hence our threaded code was never really truly concurrent.

Over the years I've had mixed feelings about threads. Some of the most challenging systems that I’ve maintained have suffered from the overuse or misunderstood impact of concurrency. Even today I have discussions around if a piece of code is truly thread-safe and although the libraries (for example, the Java Concurrency Library) have made massive improvements reducing the burden of developing with threads, it is still somewhat of a challenge to ensure that we are not calling code which is not thread-safe when we have assumed it is. This is something that is generally not easily picked up by either static analysis or software compilers.

Java Concurrency: AtomicReference

Java.util.concurrent.atomic.AtomicReference is a class designed to update variables in a thread-safe way. Why do we need the class AtomicReference? Why can we not simply use a volatile variable? And how can we use it correctly?

Why AtomicReference?

For the tool I am writing, I need to detect if an object was called from multiple threads. I use the following immutable class for this: