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.

5 Things You Probably Didn’t Know About Java Concurrency

Thread is the heart of the Java programming language. When we run a Hello World Java program, we run on the main thread. And then, we can definitely create threads easily as we need to compose our application code to be functional, responsive, and performant at the same time. Think about a web server; it simultaneously handles hundreds of requests at the same time. In Java, we achieve this using multiple threads. While threads are helpful, it is dreadful to many of the developers. That's why in this article, I will share five interesting threading concepts that the beginner and intermediate developers might not know.  

1. The Program Order and The Execution Order Are Not the Same

When we write a code, we assume the code will be executed exactly the way we write it. However, in reality, this is not the case. The Java compiler may change the execution order to optimize it if it can determine that the output won't change in single-threaded code.

Let’s Use Optional to Fix Our Method Contract

A method is a contract; when we define one, we put our thoughts into it. We specify the parameters with their type and also a return type. When we invoke a method, we expect it to behave according to the contract. If it doesn’t, it’s a violation of the contract.

We deal with such a violation all the time. We invoke a method with its proper arguments, and we get a return. However, sometimes we end up getting a null, which is, in fact, a clear violation. We shouldn’t accept such a violation. If a method cannot return the value of the specified type, it should mention that in the method signature, the method may or may not be returning the value you are expecting. If we know it from the method signature, we then write our code accordingly.