Member-only story
Java Locks: Understanding Synchronized and ReentrantLock
When writing Java programs that use multiple threads, we need ways to control access to shared data. Java offers two main ways to do this: using the synchronized
keyword (intrinsic locks) or using the locks from the java.util.concurrent
package (like ReentrantLock
). In this article, we'll look at both approaches, their good and bad points, and when you might want to use one over the other.
What Are Locks in Java?
Before we dive in, let’s understand what locks are and why we need them:
Locks help us manage how multiple threads access shared resources. When one thread has a lock, other threads must wait until the lock is free before they can access the same resource. This helps prevent problems like:
- Race conditions: When two threads try to change the same data at the same time
- Data corruption: When incomplete operations leave data in a wrong state
- Inconsistent reads: When a thread reads data while another thread is changing it
Java provides two main types of locks to help us solve these problems.
Intrinsic Locks (synchronized)
Intrinsic locks (also called monitor locks) are the original way to handle thread…