

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between ReentrantLock and Synchronized in Java
There are two ways to get a lock on the shared resource by multiple threads. One is Reentrant Lock (Or ReadWriteLock ) and the other is by using the Synchronized method.
ReentrantLock class has been provided in Java concurrency package from Java 5.
It is the implementation of Lock interface and According to java docs, implementation of Lock interface provides more extensive operation than can be obtained using synchronized method.
Sr. No. | Key | ReentrantLock | Synchronized |
---|---|---|---|
1 | Acquire Lock | Reentrant lock class provides lock() methods to get a lock on the shared resource by thread | You need to just write synchronized keyword to acquire a lock |
2 | Release Lock | To release lock , programmers have to call unlock() method | It is done implicitly |
3 | Ability to interrupt | lockInterruptibly() method can be used to interrupt the thread | There is no way to interrupt the thread |
4 | Fairness | Constructor of this class has fairness parameter. If it is set to true then locks favor granting access to the longest-waiting * thread | Lock does not guarantee any particular access orde |
5 | Lock Release Order | Lock can be released in any order | Lock should be released in the same order in which they were acquired |
Example of ReentrantLock
public class ReentrantLockExample implements Runnable{ private Lock lock=new ReentrantLock(); @Override public void run() { try { lock.lock() //Lock some resource } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
Example of SynchronizedLock
public class SynchronizedLockExample implements Runnable{ @Override public void run() { synchronized (resource) { //Lock some resource } } }
- Related Questions & Answers
- Difference between Synchronized ArrayList and CopyOnWriteArrayList in Java
- Difference between Concurrent hash map and Synchronized hashmap in Java
- synchronized Keyword in Java
- Difference between Go and Java.
- Difference between Java and JavaScript.
- Difference Between C++ and Java
- Difference between Java and C language
- Difference between ArrayList and CopyOnWriteArrayList in Java
- Difference between HashMap and ConcurrentHashMap in Java
- Difference between HashTable and HashMap in Java
- Difference between ODBC and JDBC in Java
- Difference between super() and this() in Java
- Difference between Object and Class in Java
- Difference between HashMap and HashTable in Java.
- Difference between StringBuilder and StringBuffer in Java
Advertisements