Differences Between Java Lock Interface and synchronized Keyword
This article explains the key differences between Java's Lock interface and the synchronized keyword, covering their nature, lock acquisition and release mechanisms, fairness, ability to query lock status, usage scenarios, and includes example code demonstrating each approach.
In Java concurrent programming, developers often need to lock code blocks or methods, and the two common mechanisms are the Lock interface and the synchronized keyword. Understanding their differences is useful for everyday coding and interview preparation.
First, Lock is a Java interface provided by the JDK API, while synchronized is a built‑in language keyword.
Second, a thread that acquires a synchronized lock automatically releases it after the synchronized block or method finishes, whereas a Lock must be released manually. The following examples illustrate both approaches.
package com.sample.multithread.base;
// 使用synchronized关键字加锁
public class SynchronizedDemo {
private long count = 0;
// 计数器加1
public synchronized void add() {
count++;
}
// 获取计数器的值
public synchronized long getCount() {
return count;
}
}The synchronized version results in concise code because the language handles lock acquisition and release automatically.
package com.sample.multithread.base;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
// 使用接口Lock加锁
public class LockDemo {
private long count = 0;
// Lock的接口实现类,通常使用ReentrantLock
private Lock lock = new ReentrantLock();
// 计数器加1
public void add() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
// 获取计数器的值
public long getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}In contrast, the Lock version requires explicit calls to lock() and unlock() , making the code longer but offering more control.
Additional differences include:
synchronized automatically releases the lock even if an exception occurs or the thread calls wait() .
Lock provides tryLock() to test lock availability and can specify a timeout, features not available with synchronized.
synchronized can lock both methods and code blocks, whereas Lock can only lock code blocks.
synchronized is a non‑fair lock with no fairness option; Lock defaults to non‑fair but can be configured as a fair lock.
For simple concurrency scenarios, synchronized is usually sufficient; for high contention or fine‑grained control, Lock is more appropriate.
A summary table (shown in the original article) compares these points side by side.
References: the article cites GeeksforGeeks and provides additional recommended readings on related topics.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.