Non-blocking algorithms
As a final concept of concurrent programming, let’s look at non-blocking algorithms. These algorithms help us achieve thread safety without having to use the locking mechanisms we previously covered, such as synchronized
methods and synchronized blocks. There are three types of non-blocking algorithms – lock-free, wait-free, and obstruction-free. Although their names are self-describing, let’s take a closer look.
Modern CPUs support atomic operations, and Java includes several atomic classes that we can use when implementing non-blocking algorithms.
Atomic operations
These are operations that are executed by modern CPUs as a single, finite step that ensures consistency without the need for locks.
Here is a code snippet that illustrates how to use AtomicInteger
:
import java.util.concurrent.atomic.AtomicInteger; public class Counter { private AtomicInteger count = new AtomicInteger(0); ...