SlideShare a Scribd company logo
1 of 10
When a thread fails to acquire the lock, it gets added to a waiting
queue. It can be unblocked either by the thread holding the lock or by
interrupting it.
When we call ReentrantLock.lock(), we acquire lock in a non-interruptible mode which means
even if the thread waiting in queue is interrupted or unparked, it is going to simply retry
acquiring the lock. This goes on, resulting in blocking and unblocking of the thread till it
acquires the lock.
We can try acquiring lock in exclusive interruptible mode using ReentrantLock.lockInterruptibly() in which
case if the thread in waiting is interrupted by some other thread it will result in InterruptedException thus
there won’t be any retry. If the thread is unparked as a result of release of lock then it is going to retry
acquiring lock.
A reentrant lock is a mutually exclusive lock similar to synchronized keyword. But with more
capabilities than the synchronization.
As you know thread scheduler always tries to give the priority to the maximum priority thread.
Sometimes it may be caused to the starvation state. But The Reentrant lock assured
the fairness to the threads than the synchronization. Also, reentrant lock can provide a lock to
longest waiting thread in the system
How does it work?
ReentrantLock object is created as an instance variable of the class. It is an implementation of
the Lock interface. java.util.concurrent.locks package consists of both methods. You may feel the
name of this reentrant lock is a bit awkward. But its functionality is defined by its name also.
The ReentrantLock allows a thread to acquire a lock it already owns multiple time recursively.
The number of times that a thread acquires a lock is stored in a hold count variable. When the
thread acquires the lock, the hold count is increased by 1, and when it releases the lock, hold
count is decreased by 1. The lock is completely relinquished if hold count is 0. So there must be
a call to unlock() for every call to lock().
Difference between Synchronized keyword and ReentrantLock in Java
If you want to lock a thread interruptible and ofcause without a timeout method I
recommend you to use the ReentrantLock. If you trying to lock a thread interruptibly
using the synchronized way you need to block the thread infinitely.
1.The synchronized keyword does not support the fairness — When using ReentrantLock you can
call the fairness property and it will lock to the longest waiting thread
2.The second difference between synchronized and ReentrantLock is the lock() method.
ReentrantLock provides a convenient lock() method, which acquires lock only if its available or not
held by any other thread. This reduces the blocking of thread waiting for lock-in Java application.
3.As mentioned above ReentrantLock provides a method called lockInterruptibly() which can be
used to interrupt thread when the thread is waiting for the lock. But when using synchronized, the
thread can be blocked waiting for a lock for a long time.
public void some_method()
{
reentrantlock.lock();
try
{
//Do some work
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
reentrantlock.unlock();
}
}
ReentrantLock() Example
•lock(): Call to the lock() method increments the hold count by 1 and gives the lock to the thread if the shared
resource is initially free.
•unlock(): Call to the unlock() method decrements the hold count by 1. When this count reaches zero, the resource is
released.
•tryLock(): If the resource is not held by any other thread, then call to tryLock() returns true and the hold count is
incremented by one. If the resource is not free, then the method returns false, and the thread is not blocked, but exits.
•tryLock(long timeout, TimeUnit unit): As per the method, the thread waits for a certain time period as defined by
arguments of the method to acquire the lock on the resource before exiting.
•lockInterruptibly(): This method acquires the lock if the resource is free while allowing for the thread to be
interrupted by some other thread while acquiring the resource. It means that if the current thread is waiting for the
lock but some other thread requests the lock, then the current thread will be interrupted and return immediately
without acquiring the lock.
•getHoldCount(): This method returns the count of the number of locks held on the resource.
•isHeldByCurrentThread(): This method returns true if the lock on the resource is held by the current thread.
ReentrantLock() Methods
It is recommended practice to always immediately follow a call to lock with
a try block, most typically in a before/after construction such as:
class X {
private final ReentrantLock lock = new ReentrantLock();
// ... public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
} }
Java reentrant lock tutorial by jeetendra mandal

More Related Content

Similar to Java reentrant lock tutorial by jeetendra mandal

econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreadingTuan Chau
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter KitMark Papis
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
 
Thread safety and code syncronization
Thread safety and  code syncronizationThread safety and  code syncronization
Thread safety and code syncronizationSrinivas Reddy
 
CS844 U1 Individual Project
CS844 U1 Individual ProjectCS844 U1 Individual Project
CS844 U1 Individual ProjectThienSi Le
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 

Similar to Java reentrant lock tutorial by jeetendra mandal (20)

econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Locks
LocksLocks
Locks
 
Java tips
Java tipsJava tips
Java tips
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
 
Thread safety and code syncronization
Thread safety and  code syncronizationThread safety and  code syncronization
Thread safety and code syncronization
 
CS844 U1 Individual Project
CS844 U1 Individual ProjectCS844 U1 Individual Project
CS844 U1 Individual Project
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
READER/WRITER SOLUTION
READER/WRITER SOLUTIONREADER/WRITER SOLUTION
READER/WRITER SOLUTION
 

More from jeetendra mandal

Eventual consistency vs Strong consistency what is the difference
Eventual consistency vs Strong consistency what is the differenceEventual consistency vs Strong consistency what is the difference
Eventual consistency vs Strong consistency what is the differencejeetendra mandal
 
Batch Processing vs Stream Processing Difference
Batch Processing vs Stream Processing DifferenceBatch Processing vs Stream Processing Difference
Batch Processing vs Stream Processing Differencejeetendra mandal
 
Difference between Database vs Data Warehouse vs Data Lake
Difference between Database vs Data Warehouse vs Data LakeDifference between Database vs Data Warehouse vs Data Lake
Difference between Database vs Data Warehouse vs Data Lakejeetendra mandal
 
Difference between Client Polling vs Server Push vs Websocket vs Long Polling
Difference between Client Polling vs Server Push vs Websocket vs Long PollingDifference between Client Polling vs Server Push vs Websocket vs Long Polling
Difference between Client Polling vs Server Push vs Websocket vs Long Pollingjeetendra mandal
 
Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...
Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...
Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...jeetendra mandal
 
Difference Program vs Process vs Thread
Difference Program vs Process vs ThreadDifference Program vs Process vs Thread
Difference Program vs Process vs Threadjeetendra mandal
 
Carrier Advice for a JAVA Developer How to Become a Java Programmer
Carrier Advice for a JAVA Developer How to Become a Java ProgrammerCarrier Advice for a JAVA Developer How to Become a Java Programmer
Carrier Advice for a JAVA Developer How to Become a Java Programmerjeetendra mandal
 
How to become a Software Tester Carrier Path for Software Quality Tester
How to become a Software Tester Carrier Path for Software Quality TesterHow to become a Software Tester Carrier Path for Software Quality Tester
How to become a Software Tester Carrier Path for Software Quality Testerjeetendra mandal
 
How to become a Software Engineer Carrier Path for Software Developer
How to become a Software Engineer Carrier Path for Software DeveloperHow to become a Software Engineer Carrier Path for Software Developer
How to become a Software Engineer Carrier Path for Software Developerjeetendra mandal
 
Microservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design PatternMicroservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design Patternjeetendra mandal
 
Event Driven Software Architecture Pattern
Event Driven Software Architecture PatternEvent Driven Software Architecture Pattern
Event Driven Software Architecture Patternjeetendra mandal
 
Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...
Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...
Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...jeetendra mandal
 
Observability vs APM vs Monitoring Comparison
Observability vs APM vs  Monitoring ComparisonObservability vs APM vs  Monitoring Comparison
Observability vs APM vs Monitoring Comparisonjeetendra mandal
 
Disaster Recovery vs Data Backup what is the difference
Disaster Recovery vs Data Backup what is the differenceDisaster Recovery vs Data Backup what is the difference
Disaster Recovery vs Data Backup what is the differencejeetendra mandal
 
What is Spinnaker? Spinnaker tutorial
What is Spinnaker? Spinnaker tutorialWhat is Spinnaker? Spinnaker tutorial
What is Spinnaker? Spinnaker tutorialjeetendra mandal
 
Difference between Github vs Gitlab vs Bitbucket
Difference between Github vs Gitlab vs BitbucketDifference between Github vs Gitlab vs Bitbucket
Difference between Github vs Gitlab vs Bitbucketjeetendra mandal
 

More from jeetendra mandal (20)

what is OSI model
what is OSI modelwhat is OSI model
what is OSI model
 
What is AWS Cloud Watch
What is AWS Cloud WatchWhat is AWS Cloud Watch
What is AWS Cloud Watch
 
What is AWS Fargate
What is AWS FargateWhat is AWS Fargate
What is AWS Fargate
 
Eventual consistency vs Strong consistency what is the difference
Eventual consistency vs Strong consistency what is the differenceEventual consistency vs Strong consistency what is the difference
Eventual consistency vs Strong consistency what is the difference
 
Batch Processing vs Stream Processing Difference
Batch Processing vs Stream Processing DifferenceBatch Processing vs Stream Processing Difference
Batch Processing vs Stream Processing Difference
 
Difference between Database vs Data Warehouse vs Data Lake
Difference between Database vs Data Warehouse vs Data LakeDifference between Database vs Data Warehouse vs Data Lake
Difference between Database vs Data Warehouse vs Data Lake
 
Difference between Client Polling vs Server Push vs Websocket vs Long Polling
Difference between Client Polling vs Server Push vs Websocket vs Long PollingDifference between Client Polling vs Server Push vs Websocket vs Long Polling
Difference between Client Polling vs Server Push vs Websocket vs Long Polling
 
Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...
Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...
Difference between TLS 1.2 vs TLS 1.3 and tutorial of TLS2 and TLS2 version c...
 
Difference Program vs Process vs Thread
Difference Program vs Process vs ThreadDifference Program vs Process vs Thread
Difference Program vs Process vs Thread
 
Carrier Advice for a JAVA Developer How to Become a Java Programmer
Carrier Advice for a JAVA Developer How to Become a Java ProgrammerCarrier Advice for a JAVA Developer How to Become a Java Programmer
Carrier Advice for a JAVA Developer How to Become a Java Programmer
 
How to become a Software Tester Carrier Path for Software Quality Tester
How to become a Software Tester Carrier Path for Software Quality TesterHow to become a Software Tester Carrier Path for Software Quality Tester
How to become a Software Tester Carrier Path for Software Quality Tester
 
How to become a Software Engineer Carrier Path for Software Developer
How to become a Software Engineer Carrier Path for Software DeveloperHow to become a Software Engineer Carrier Path for Software Developer
How to become a Software Engineer Carrier Path for Software Developer
 
Events vs Notifications
Events vs NotificationsEvents vs Notifications
Events vs Notifications
 
Microservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design PatternMicroservice Architecture Software Architecture Microservice Design Pattern
Microservice Architecture Software Architecture Microservice Design Pattern
 
Event Driven Software Architecture Pattern
Event Driven Software Architecture PatternEvent Driven Software Architecture Pattern
Event Driven Software Architecture Pattern
 
Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...
Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...
Top 5 Software Architecture Pattern Event Driven SOA Microservice Serverless ...
 
Observability vs APM vs Monitoring Comparison
Observability vs APM vs  Monitoring ComparisonObservability vs APM vs  Monitoring Comparison
Observability vs APM vs Monitoring Comparison
 
Disaster Recovery vs Data Backup what is the difference
Disaster Recovery vs Data Backup what is the differenceDisaster Recovery vs Data Backup what is the difference
Disaster Recovery vs Data Backup what is the difference
 
What is Spinnaker? Spinnaker tutorial
What is Spinnaker? Spinnaker tutorialWhat is Spinnaker? Spinnaker tutorial
What is Spinnaker? Spinnaker tutorial
 
Difference between Github vs Gitlab vs Bitbucket
Difference between Github vs Gitlab vs BitbucketDifference between Github vs Gitlab vs Bitbucket
Difference between Github vs Gitlab vs Bitbucket
 

Recently uploaded

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Java reentrant lock tutorial by jeetendra mandal

  • 1.
  • 2. When a thread fails to acquire the lock, it gets added to a waiting queue. It can be unblocked either by the thread holding the lock or by interrupting it.
  • 3. When we call ReentrantLock.lock(), we acquire lock in a non-interruptible mode which means even if the thread waiting in queue is interrupted or unparked, it is going to simply retry acquiring the lock. This goes on, resulting in blocking and unblocking of the thread till it acquires the lock.
  • 4. We can try acquiring lock in exclusive interruptible mode using ReentrantLock.lockInterruptibly() in which case if the thread in waiting is interrupted by some other thread it will result in InterruptedException thus there won’t be any retry. If the thread is unparked as a result of release of lock then it is going to retry acquiring lock.
  • 5. A reentrant lock is a mutually exclusive lock similar to synchronized keyword. But with more capabilities than the synchronization. As you know thread scheduler always tries to give the priority to the maximum priority thread. Sometimes it may be caused to the starvation state. But The Reentrant lock assured the fairness to the threads than the synchronization. Also, reentrant lock can provide a lock to longest waiting thread in the system How does it work? ReentrantLock object is created as an instance variable of the class. It is an implementation of the Lock interface. java.util.concurrent.locks package consists of both methods. You may feel the name of this reentrant lock is a bit awkward. But its functionality is defined by its name also. The ReentrantLock allows a thread to acquire a lock it already owns multiple time recursively. The number of times that a thread acquires a lock is stored in a hold count variable. When the thread acquires the lock, the hold count is increased by 1, and when it releases the lock, hold count is decreased by 1. The lock is completely relinquished if hold count is 0. So there must be a call to unlock() for every call to lock().
  • 6. Difference between Synchronized keyword and ReentrantLock in Java If you want to lock a thread interruptible and ofcause without a timeout method I recommend you to use the ReentrantLock. If you trying to lock a thread interruptibly using the synchronized way you need to block the thread infinitely. 1.The synchronized keyword does not support the fairness — When using ReentrantLock you can call the fairness property and it will lock to the longest waiting thread 2.The second difference between synchronized and ReentrantLock is the lock() method. ReentrantLock provides a convenient lock() method, which acquires lock only if its available or not held by any other thread. This reduces the blocking of thread waiting for lock-in Java application. 3.As mentioned above ReentrantLock provides a method called lockInterruptibly() which can be used to interrupt thread when the thread is waiting for the lock. But when using synchronized, the thread can be blocked waiting for a lock for a long time.
  • 7. public void some_method() { reentrantlock.lock(); try { //Do some work } catch(Exception e) { e.printStackTrace(); } finally { reentrantlock.unlock(); } } ReentrantLock() Example
  • 8. •lock(): Call to the lock() method increments the hold count by 1 and gives the lock to the thread if the shared resource is initially free. •unlock(): Call to the unlock() method decrements the hold count by 1. When this count reaches zero, the resource is released. •tryLock(): If the resource is not held by any other thread, then call to tryLock() returns true and the hold count is incremented by one. If the resource is not free, then the method returns false, and the thread is not blocked, but exits. •tryLock(long timeout, TimeUnit unit): As per the method, the thread waits for a certain time period as defined by arguments of the method to acquire the lock on the resource before exiting. •lockInterruptibly(): This method acquires the lock if the resource is free while allowing for the thread to be interrupted by some other thread while acquiring the resource. It means that if the current thread is waiting for the lock but some other thread requests the lock, then the current thread will be interrupted and return immediately without acquiring the lock. •getHoldCount(): This method returns the count of the number of locks held on the resource. •isHeldByCurrentThread(): This method returns true if the lock on the resource is held by the current thread. ReentrantLock() Methods
  • 9. It is recommended practice to always immediately follow a call to lock with a try block, most typically in a before/after construction such as: class X { private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body } finally { lock.unlock() } } }