The synchronized keyword
As we’ve just seen, working with many threads can bring potential new problems, such as data integrity. The synchronized keyword is a Java keyword that uses a lock mechanism to achieve synchronization. It is used to control access to critical sections of code for different threads. When a thread is inside a synchronized method or block, no other thread can enter any of the synchronized methods for the same object.
To understand the need for synchronization, let’s consider another simple concurrent counting scenario where unexpected outcomes can occur. We have a class named Count
with a static counter
variable. This class also has a method, incrementCounter
, which increments the value of counter
by one:
public class Count { static int counter = 0; static void incrementCounter() { int current = counter; ...