Happens-Before In Java Or How To Write a Thread-Safe Application

Multithreading is the most complex part of Java. Happens-before is a relation that gives a guarantee of allowing the writing of predictable code in multithreading a reality. Such code is also known as thread-safe code. Unfortunately, Oracle Java documentation about this notion is hard to read. So in this article, I'll mainly explain what happens-before is in human language and provide detailed examples.

Happens-Before Solves the Main Multithreading Problem

Before we start learning the happens-before notion, we have to understand the reason for creating it. Once multithreading comes to the scene, your code might become inconsistent because shared objects between threads might have different and unpredictable values. Let's review a simple example. In that example, we will update values in one thread and read and print them in another.

CategoriesUncategorized