Introduction to Mutual Exclusion in Java
Every multithreaded program is eventually going to hit the problem of two concurrent threads trying to read, write or modify an object stored in a shared memory.
Java offers many tools to deal with this problem, one better than the other, each coming with its own set of pros and cons.
This article is going to introduce the problem, give an overview of the available solutions (always with examples!) and introduce you, my dear reader, to the world of concurrent programming in Java.
Understanding the problem
Let’s analyze the code below - a simple counter with two methods increment() and get(). When there is only one thread
, everything runs in the order it appears in the code. Each instruction is executed only after the previous one has finished,
the developer has full control over the order of execution.
public class Counter {
private int count = 0;
public void increment() {
count++;
}
public int get() {
return count;
}
}
