- Podcasts
- The Java Developers Hub
- Java Concurrency Locks Explained | ReentrantLock, ReadWriteLock, StampedLock, Semaphore & Condition
Java Concurrency Locks Explained | ReentrantLock, ReadWriteLock, StampedLock, Semaphore & Condition
The Java Developers Hub
- December 3, 2026
- 1 h 20 min
- Episode 12
About this episodeManaging access to shared resources is one of the biggest challenges in multithreaded Java applications. When multiple threads attempt to…
- Understanding thread synchronisation and locking in Java.
- What locks are and why they are important.
- Understanding ReentrantLock and its advantages over intrinsic synchronisation.
- Acquiring and releasing locks safely.
- Using tryLock() for controlled lock acquisition.
- Understanding ReadWriteLock and concurrent read operations.
- How ReentrantReadWriteLock works.
- Understanding StampedLock and optimistic reading.
- What semaphores are and how Semaphore controls resource access.
- Understanding permits and thread coordination.
- Using Condition to coordinate waiting and signalling between threads.
- Differences between Java locking mechanisms.
- Avoiding deadlocks and common synchronisation mistakes.
- Best practices for building thread-safe Java applications.
- Intermediate and advanced Java developers.
- Backend engineers building concurrent applications.
- Software engineers interested in multithreading.
- Computer science students studying concurrency.
- Developers preparing for senior Java engineering interviews.
- Anyone interested in thread safety and synchronisation.
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Java Concurrency Locks Explained | ReentrantLock, ReadWriteLock, StampedLock, Semaphore & Condition
So welcome back Coder Army to our Java series and now we are continuing our multithreading series in which today we are going to study alternative locking techniques. We had seen synchronized locks, right? We will see which locks exist in its alternative and in Java. We will also see why they exist. You will have a lot of fun, you will get to learn a lot. So let's quickly go to the screen and start. Yes, so basically locks in Java. We had studied about synchronized, right? Then why are we studying about other types of locks? There are many reasons, we will discuss them. But before that, we should know that a lock name, not locks actually, a lock name, we have an interface in Java, okay? Which comes in Java's concurrency package. This is an interface. And what does this interface say? Obviously, interface is a contract. So it will say that whichever class will implement me, it will have to provide a contract of two things. Or it will have to provide implementation of two methods. One is how to lock something and the other is how to unlock something.
Apart from this, there will be some optional methods. We have a lock interface in which two methods are defined which will be declared and left. The defined method will do its classes which will implement this lock. So, we have a lock method and an unlock method. Now, we will see those methods and understand the reason why the lock interface exists when we had the synchronized block.
So see, in our synchronized block, if I talk about the first limitation, then I didn't have any control over the log. So I can write no control over log. Okay, what does it mean? It means, how do we make a synchronized block? Let's say if we have written before any method, then we would have written synchronized. And the method name will be void something f1 And we used to do some work here Now not having control means that let's say we have a thread t1 which tries to acquire the lock But as soon as it tries it finds out that the lock is acquired by another thread So where does our t1 go? It goes straight to waiting state What happens is that I want a control that if T1 does not get a lock, then it should do something else. Something like, if it is able to acquire a lock, then it is good, otherwise it should do something else. I cannot control this on my synchronized block, but I can control it on my lock interface. Now we will see how we can do it. Apart from this, if I talk about another pointer, We didn't even have a timeout there, no timeout. Timeout means, I can't say that wait for 2 seconds for a lock. Like for example, our T1 thread is waiting here. I'm saying that if you get a lock after waiting for 2 seconds, then it's okay, let's do something else. So it wasn't like that either, if I tried to acquire a lock, I would get it, if I didn't get it, I would.
That this is your synchronized block and multiple threads want to come in it So T1, T2, T3, T4 You know that only one thread will be able to enter, so let's say your T1 thread enters And as soon as T2, T3, T4 will try to acquire in lock, they will go into blocking queue Now the problem of fairness is that, let's assume that the threads T2, T3, T4 and T1, what will be their order to arrive here? So let's say T2 arrived here in the first second, then let's say T3 arrived here in the second second, then it came in the third second and T1 came in the fourth second. But who will get the lock? There is no order for this. Now see T1 got it first, right? Now let's say T1 finished his work, T1 exited from here, then let's say T3 got the lock. So let's say T3 gets the lock this time. So I'll write T3 in our common pool, in shared resource. If T3' s work is also done, then maybe our operating system and.
So the problem is that even though T2 arrived first, maybe it got the lock last. So we call this no fairness. And because of this, a major problem can happen in our multithreading, which we call starvation. Okay? You might have heard this name in the operating system, that how a thread gets starvation.
You can assume that there is a thread, T2, which is waiting to acquire resources, basically to enter this critical section, but it is not getting that resource. Because another thread is coming, now it is possible that T2 was about to come, the rest of the thread got over, but immediately a T5 thread came and it also got the resource.
So T2 can wait for a long time and it can get starvation. Starvation means that we won't get any resource, and we won't be able to do any work for a long time. So, there was no fairness in our synchronized block. Any thread could have been entered in a critical section. Our operating system and our CPU used to decide that.
Okay? Now let's go back to our lock interface. I told you in Java that we have a lock interface. Which says that whoever implements me, he has two methods. One is the lock method and the other is the unlock method. We have to provide their implementation. Now obviously you must be understanding from the name. What will the lock method say? If you need permission to enter in a critical section, then you will call.
Now sometimes blocking state and waiting state confuse each other. We say that it will go in blocking state but it is waiting. Now don't get confused. You have to keep it simple that if a thread tries to acquire a lock to enter a critical section and it doesn't get a lock, then it is in a blocking state. And secondly, if I call a method on a thread, specifically it is called wait, then it goes to our waiting queue.
Use it in naming convention, we can say that the thread is waiting for the lock acquisition. Because as soon as a thread releases a lock, then what happens to the other thread? It tries to acquire that thread again, so we say that T1 was waiting till then, but actually it is in a blocking state. So now you understand that the lock interface is going to provide us more flexibility than our simple synchronized interface. That's why in java we use the lock interface more in production. Sometimes we use the synchronized interface because it is very simple. So if I name you which locks we are going to read here. So we are going to read only four types of locks. One of them is the reentrant lock. This is the most commonly used lock. Basically, this is the most commonly used after synchronized.
After this, we will read read-write lock. After this, we will read stamped lock. And finally, we will read sema 4. Now, SEMA 4 doesn't work exactly like a lock, but we'll see the difference in that as well. You'll only hear it as an almost lock. But mainly, we're going to read about these four things. Re-entrant lock, read-write lock, stamp-ed lock, and SEMA 4. Okay, so let's start with our re-entrant lock. Now all these locks are very weird to hear like reentrant, stamped, readwrite and semaphore But they are very simple. In fact it is very interesting to understand. Now reentrant lock is the most common type of lock. I will tell you why its name is reentrant. Before that let's see how it works. So you know our interface name is lock. So you will simply write let's say lock type. We have made a lock. Small lock equal to new. Now here will come the name of our class which is reentrant lock. reentrant lock.
Whatever your critical section is, the one you believe to be the critical section, you should enter only one thread in it, right? So now you don't need to write a synchronized block, nor do you need to write it on a method. What you will do is, whenever you are going to enter in your imaginary synchronized block, before that, you will ask the thread to acquire the lock.
Line should be lock.lock So basically on this lock reference variable I have applied the lock method. So basically what is going to come down here is the critical section. So until I unlock, one thread will go in front of this line at once. So it works exactly like a critical section. Now what you can do is you can write some code here. Whatever the code of your critical section is. And finally you can do lock.unlock And you will exit from here. So this is exactly the same as the previous one. This is a completely synchronized block. Here you had written synchronize outside. Like we were writing earlier. Instead of that you did lock.lock. and finally lock.unlock. And this middle part is the part that you want to execute in one go. This will work, but Java documents are not safe. Now imagine that we are logging and unlocking on our own. So we would be able to understand that if we have logged but forgot to unlock. So if we don't unlock, you know what will happen? One thread will keep executing the entire code and the other thread will not be able to enter it. Second problem, if there is an exception here, even though I have unlocked, But if there is an exception, then what will happen? We will come straight out of here and we will not even release the lock, because we have not unlocked it, we have to do it manually here. But in the synchronized block we had, we did not have to do anything manually. There is a manual work here. So basically, as soon as the exception comes, the rest of our thread T2, T3, which were waiting here, will keep waiting. Now again, wait means it was in the blocking state here and it will remain there. Because some other thread acquired the lock, but there was an exception in between. So Java's docs says, don't write like this. Now change it a little bit by using try catch block So obviously the first line will be lock.lock What did you do? You locked the bottom section Now write whatever code you will write in the try block Write your normal code here, basically this part Whatever is your critical section And write a finally block here To release your lock and write lock. unlock something like this and we know the special thing about finally that no matter what happens, whether there is an exception or not, finally the block is always executed. There is a rare case where JVM is stopped, but that is a very rare case, but normally finally the block is always executed.
So the preferred way is to write something like this. Okay, so this is a very simple syntax of the reinterpret lock. Let's go to the code once and see. Yes, so we have come to our demo.java. So I am making a simple class, let's say resource So let's say I make a method in it, void F1 In which I want to enter only one thread at a time But normally I would have written a synchronized block here, now I don't want to execute it So let's first execute whatever thread is entering in it You know thread dot current thread dot get name And here I will write entered And here we will do something, to mimic it I can do sleep. So let's say we put it in try catch block. We will write try thread.sleep thread.sleep Let's say we make it sleep for 2 seconds.
Now we want to enter one thread at a time in it. So what I have to do is, I can use synchronize here but I am not using it because I am talking about locks. So first I will create an object of regenerateLock. So I will write lock type which is an interface. So as soon as I write lock, what we get here is java.util.concurrent.lock.lockPackage. So this is basically our entire package name and this is our interface. You can go to interface lock and it will give you all the methods like lock method and unlock method So we will do lock lock equal to let's say new and I am going to make a re-intraint lock type object So this is our class re-intraint lock It starts with public class re-entrant log which implements our log Now let's see how we can log it As soon as my method started, I put log on this log object And as soon as I exit from here, I did lock.unlock something like this. I had said that all the parts inside this, basically before lock.lock, sorry, and before lock.unlock. This will complete our critical section. And what Java suggests is that you write this critical section in try block. So we write it like this, try. And what Java recommends is that you don't write it like this. Write this entire critical section in try block. So that even if there is an exception, our unlock works. So I have written it like this. Let's format it. Something like this. And here I will write it in my finally. Okay, finally. Something like this. You know that catch is optional. We saw this in exception handling. So you can just write try and finally. Here I have unlocked the lock. Now I am assuming that if I make multiple threads to execute f1, then only one thread will go in it at a time.
And here we can say, we can give a lambda expression, let's say we don't take any input and we will exit directly. For this resource's f1 method, I will have to make an object of this resource. So I can write, let's say, resource R1 equal to new resource. Something like this. And I will simply write, call the f1 method of R1 object. Something like this.
So let's run it and see what our expected output should be. It will enter only one thread in one go. Entered thread 0, thread 0 exited, then thread 1, then thread 1 exited, then thread 2, and then thread 2 exited as well. So see, I was able to enter only one thread in one go, which means our re-intraint lock is working properly. Now an interesting thing, as we read in synchronized that who are we actually locking?
So we have read that every object, like here we have a class called resource and we have made its object R1. Every object has a lock, so R1 will have its own lock, which these threads will try to acquire. These T1, T2, T3 threads will try to acquire. And whichever thread gets its lock, it will enter its critical section and when the synchronized block is finished, it will automatically release the lock for the second thread. That is, every R1 object will have a lock with details that which thread has occupied it. Now here the responsibility changes a bit. Now we are not doing anything with the resource. We make a new object, reentrantLock of type lock. Now I am saying that in this lock object, if you call lock, then you will acquire the lock. And when you call unlock, then you will release the lock. We will have to do this manually. So Java has made a whole class of its own. We will see what the benefits are. But I hope you understood who we are locking here. Now we are not locking the resource object. We are actually using a new object, a reentrantLock type object.
Now we know how reintraintLock works but now the biggest question is why? When synchronize was working very easily then what is the benefit of it? Why should we work manually? Let's do it because reintraintLock unlocks a lot of features and the most interesting feature of it is tryLock. What does it say? You can write a code like this. Let's say your object's name is lock then you will write if lock.tryLock Now what.
If you get it, enter it in the critical section, do whatever you want to do. Here you can write else if you don't get the lock, then what to do? So here you can write an alternative mechanism. By chance I don't get the lock, so I want to perform some other work. I don't want my thread to go into a blocking state. So here I can do this work which I couldn't do with synchronize and this is very useful thing. So here your normal code will come that try do something and finally you will unlock lock.unlock. This is the code that if you acquire lock but if you don't acquire then your else will be executed.
But here we have to remember that with great power comes great responsibility. If you forget to unlock call, then your thread will remain locked and the rest of the thread will not be able to enter. So it is our manual responsibility to call it and write it in the block so that in case there is an exception in this try, then also this block is executed and our.
Let's say one thread is T1, can acquire this lock multiple times. So I can write it as same thread can acquire lock multiple times. Now what does it mean? Let's understand the meaning of this. It means that your lock object, let's say this lock, what you can do is you can write a code like this. First you will do lock, lock.lock once. You can lock it again, lock.lock twice. You can lock it again, lock.lock three times. Basically, one thread can lock this lock object again and again, like we did three times here. But now the condition is that when you perform the work of the critical section, after that you will have to release it three times. So you will write unlock once, unlock twice and unlock three times because you have to This is the code you have to write Now what is the benefit of this? It seems unnecessary to see. If you get a lock after locking once, then why do you have to lock 3 times? The benefit is that suppose I have this type of code. Let's say I have a method A. I have written a method A code here. First of all, it will acquire the lock. We will write lock.lock. Now consider that there will be an object of the retrained lock type which will be declared on the top. Now what we do here, in our try block, we call a new method b. Something like this. And finally, we release the lock. We write lock.unlock. Something like this. I will bring it down a little bit. So this is our method a. Now you think, the method I called here will look like we have method B and I want this to work in lock as well. So I can acquire the lock again here. I can write lock.lock. And here I will do something of my own. Let's say its try block. Do something here. And then what do we do? Finally, I release this too. I write lock.unlock. Something like this. Now think, when I execute this run method, I didn't occupy the lock twice.
On this lock method, I'm taking a lock again. Meaning I'm taking the same thread. Because the same thread T1 that I entered here, the same thread T1 is not taking a lock again. Okay. It will perform its work, we will unlock it once, and after that the method is finished, then we will go back here, the try block here is finished, then we will come to finally, and then we will unlock it again. So we took lock twice, we unlocked twice, and then where did we finally come? We came out of our whole method a. Right? This is absolutely possible in the reintrend lock. There are some locks that we will study in the future, in which this is not possible. If you do this, then you will go to the deadlock, your thread will go to the deadlock. That you can't do the same lock again and again on the same thread. But you can do this in this. Interestingly, the synchronized block that we were reading till now, that is also a re-in-trend. You can do this in synchronized as well. So basically you can write such a code in synchronized as well. So basically you can write such a code in synchronized as well. That if this method was synchronized, I would have put a synchronized keyword here. So I don't need to lock and unlock it by myself. Here in the middle, let's say I would have called the method. So I could have used my synchronized keyword in this method too. So the same thing happened that Thread T1i acquired the lock in this synchronized block. Then it went to this method B, it saw the synchronized block again. That means it would have occupied the lock on the same object again. Now both are synchronized and both are the methods of the same class, method A and method B.
Let's say the class is the method of X. So they would be occupying the lock on any object of this X, small x. So we can do it twice in that too. So synchronized works just like Rintrend. The special thing about Rintrend is that it can lock multiple times. The special thing about it is that we have a method called tryLock.
But I hope you would have understood that synchronized is also our Rintrant by default. So the special thing about Rintrant is not that you can lock it again and again. The special thing about it is that apart from synchronized, there are many other methods that give us more control over our lock. Not just Rintrant, the rest of the locks that we will read give you more control. Now let's look at all the important methods that come under the re-entrant lock. I'll write re-entrant lock here. Let's see which important methods we can.
One is very simple, we have seen dot lock, it will be useful to lock. We have seen dot unlock, it will be useful to unlock. And again, like synchronize, if you call unlock on any thread which was not already locked, it will give you an exception, illegal monitor state exception. We already know this, illegal monitor state. We have seen this exception before. Now, the third method we were talking about was tryLock. We also used this method. What you can do is, you can write a code in this if block that if tryLock, try to occupy the lock. If you get it, then do your normal work. If you don't get it, then I can write an else block here. In which I can tell the thread what that alternate can do if it doesn't acquire the lock. I can also put it directly in the blocking state. Now what I was telling you that we have an alternative to set a timeout So here I have a overloaded method of trylock And here I can give some timeout And here I can also give a time unit Now I will tell you how we can use it But mainly when I give a timeout So let's say I can write trylock Okay This is a static class and it has a lot of time related things like seconds and minutes. And here I can write my normal code which I want to execute. And when will this code be executed? If this thread gets lock in 2 seconds, then it will be done. Otherwise, we will come to our normal block. We will come directly to else block. If the lock is not acquired, then what to do? So, the normal try-lock will see that the lock can be acquired and if it can't.
But this try-lock will wait for 2 seconds and see that I can't acquire the lock right now, can I do it in the next second? It will wait for 2 seconds and if the lock is not acquired even then, it will come to else block. So, this is the difference. Now, let's see the next method a little bit below. That is our isLogged. So you can understand from the name that we will call an object. Let's say log.isLogged. And it will tell us if the object is locked by any thread or not. So it will give us a true or false answer. But we generally use this method only for monitoring and debugging purposes.
The next method is isHeldByCurrentThread. This is just to check if the current thread you are executing holds this lock. If so, then you can perform some work. So let's say you write something like if lock.isHeldByCurrentThread. So you can do lock.unlock something like this. So if the current thread occupies, then you can do something else. Although these methods are very rare. There are some other rare use methods. One is getHoldCount. Which will tell you that as I said in retrain lock, you can lock the same object multiple times with the same thread. So count will tell you that how many times a thread T1 has locked an object.
Okay, interestingly, we can understand from this that, as I said in synchronized, that the object, any object has a lock inside it and it has some details, right? Which thread has occupied me and other necessary information etc. In the same way, we have a reentrant lock here. That too carries two information. One is the information of parent thread. So I can write parent thread. That who has occupied this log. And second count. How many times it has been occupied. So if the count value is 3. Then the answer of this get hold count method should be 3. Means it has been occupied 3 times. Now it will have to be unlocked 3 times. To release this entrant log completely. Now the next very interesting method.
Fair, to find out if our re-entrant lock is running fairly or not. Now we gave the definition of fair above that if starvation is not happening then it is fair and if starvation is happening then it is not fair. Now fair means that I said this is our critical section and multiple threads are waiting here. T1, T2, T3, T4 to enter. Now it is possible that it is not able to enter because there will be another thread already here. Now after this, who should get the turn? It will depend on who came first. So it is possible then T2 and then T4. So, these were their times.
So, this means, this time, our entry should be T1, after that, we should get T3, after that, T2 and after that, T4. So, basically, according to their waiting time, as long as they were blocked for a long time, According to that, we are giving them entry. So we will say that our fair is the re-entrant lock. If this is not happening, our operating system or CPU will give entry to anyone. And it is possible that the T1 has come first, it is possible that it will get the last entry. So we will say that our lock is unfair. In unfair, you know that the chances of starvation increase. And here the chances of starvation do not happen.
So the work here is exactly like the Q data structure. Now, how can we make our reentrant law fair or unfair? It's very simple. When we write in our code, let's say, I made an object of re-entrant log, log l1 equal to new re-entrant log. If I make it simply like this, then it will always be an unfair log.
This means that it can give access to anyone to enter the thread. No one can see the waiting time or the blocking time. If you want to make a fair log, you will write reintrant log L2 equal to new again reintrant log. And here you pass true in the parameter So basically it will take a boolean variable which is its default constructor So basically our constructor will be overloaded In which it will take a boolean value to see that you have to make it fair If you pass true here then it means you have to make it fair Now whenever you call l2. isFair So your answer will be true Now remember what I said that threads will get lock from their waiting time So this is also approximate. It's not necessary that they get it every time from the exact waiting time. Because you know that Java can't hinder a lot. After all, the operating system and our CPU decide. But yes, you get it mostly. But yes, it's approximate. Sometimes it can be a little up and down. These were their important methods. I hope you understood. Now let's see our second type of lock, which was read-write lock. Now let's see what this log says. Till now, whether we have read synchronized or re-entrant, our critical section used to enter only one thread at a time. So let's say this is our critical section. If a thread is entering multiple, I'll take t1, t2, t3, whatever is waiting, it would.
But many times it will happen that you will want multiple threads to enter because it will not do any harm, right? Means it will not disturb the critical section and will not change anything for the other thread. How? You imagine that till now we call a resource. Resource can be anything. Let's say it can be a file. It could be a database. It could be a cache.
It could be any of these resources. Now tell me one thing, if I just want to read the value in these resources, I want to read something from the file, from the database, from the cache, I just want to read something. So to read, do I change something in the file, in the DB, in the cache? The answer is absolutely no. In fact, many times we make them only read only.
If I am entering a file and writing something, then I am changing something in this file. Now if in this file multiple threads T1 and T2 are inserted and both are trying to write, then either they will overwrite each other or T1 will change something that T2 will not know, there will be a problem of code visibility etc. Meaning there is an issue in writing. Writing is destructive. So read-write lock here says that if reading is safe and writing is destructive, then why not make a lock in which multiple threads that only want to read can be entered at the same time. But if a thread wants to write, then it should enter only one thread at a time. It should get that exclusive lock. Okay, so here comes our term exclusive lock.
Which just want to read the data from the critical section, then they will go to shared lock, that means they will be able to enter multiple threads at once. And if any thread wants to change anything in this resource by entering in the critical section, then we will give it an exclusive lock. That means, if the thread is T4, then it will get the only lock, no one else can enter other than that. So basically we split the lock into two parts. We have read-write-lock which is an interface itself. To implement this, we have a class called re-interrent-read-write-lock because it is re-interrent from the inside. Re-interrent means that one thread can lock one lock repeatedly. We will see about that. But it gives us two types of locks. One is read-lock and the other is write-lock. The read lock will be the shared lock And the write lock will be exclusive Because write is destructive and shared is not destructive So how do we make it? We can declare it like this Read write lock Let's say lock Equal to new I said this because there is an interface read write lock It is implemented by a class named retrent ReadWriteLock So this is its implementation ReadWriteLock And it gives me an object of ReadWriteLock Now in this read write lock, the special thing about this lock is that if multiple threads want to read, then it will allow them to enter together. If any thread wants to write, then only that thread will be allowed to enter. This means that multiple readers are allowed together. Multiple readers are allowed together. If there is one writer, then single is allowed. No one else can allow it. Let's say if there is one writer and one reader, we will not allow it. We will allow only one thread at a time. Because if we give space to the writer, we can't give space to the reader. If the writer takes the lock, then he takes the exclusive lock. Let's assume that the writer takes the exclusive lock. If a writer enters this area, then no matter how many readers or writers are waiting, they will keep doing it like a normal thread. But if a reader is included in it, then other readers will also be included in it. That means multiple readers can be here, but the writer will keep waiting. So readers are shared and writer is the only one. If a reader takes lock, then more readers can be included in it, but the writer cannot. But if a writer takes lock, then neither a reader nor any other writer can be included in it.
So this is my reinterpret read write lock class. This gives me a read-write-lock type object, which I am calling lock. Now this is a read-write-lock type interface, but till now I was reading about a lock interface. Now when you call two methods on this lock object, one is read-lock and the other is write-lock. So this will give you a read log and a write log. Read log is a shared log and this is an exclusive log. And these two objects will give you a log type k. So let's say I call it RL because it is a read log and I call it WL because it is a write log.
First of all, we have an interface called read-write-lock. Its implementation is read-write-lock. Now on this lock, which is of read-write-lock type, when I call a method read-lock, then I will get a lock type object. When I call write-lock, again I will get a lock type object. But when I called read-lock, it will give me a shared lock. And when I called write-lock, I will get an exclusive lock. We have discussed what is shared and exclusive above. Now let's see this in a good example And the name of that example is Another classic multithreading problem of Java Which we call Reader Writer Problem.
It's very simple, you must be able to understand from the name itself Suppose we have multiple writers W1, W2, W3 And we have multiple readers R1, R2, R3 Now what happens? These writers In this data, let's say there is a resource. Let's say we write something in this resource. Let's say it's a file. As you might have seen, you make a file on Google Docs and you share it with everyone. So you share it with a lot of people. Those who can edit it are all writers. And you share it with people who can only read it in read-only mode. So they become readers for you. Now all these people who can edit it, must be adding something to it. Let's say writer1 added some name here, writer2 added some more, writer3 overrides it and so on. And the readers will just read the value from here. Now if we don't use the locking mechanism, the problem will be that the multiple writers will start overwriting each other. So we will have to restrict that only one writer should be able to enter in one bar.
And if you want to read, then you can enter multiple readers at the same time. Because we don't modify anything in reading. So this is the read-write problem. This is also a classic problem. In fact, whatever is our Google Docs or any other shared resource, like we share Cache or DB, They are all solving a read write problem from inside. So if you are making your own project like Google Docs, then you have to tackle this problem from inside. Multiple readers, multiple writers and your shared resource.
And let's keep a value next to it, let's say private int value, which is initially zero. And we will try to change it in this. I'm not making a complete file for now, I'm just making an integer value like we made in the producer-consumer problem. Just remember, this problem is different from producer-consumer. Because producer-consumer problem says that one is producing and the other is consuming. And the one who consumes, snatches the value from here, changes it. But here we have reader-writers. Readers just give the value here. And the writer keeps editing the value. So the problem here is that the readers may not see any old value. Or the writer overwrites each other. Apart from this, I will make two methods here. One, let's say public int read.
Now let's do one thing, let's put a locking mechanism here. Because if multiple people enter right, then they will overwrite this value. So let's do one thing, let's put a read write lock. So I write read write lock. Let's name it ReadWriteLog, readWriteLog equal to new and you know we have a class named RentrentReadWriteLog something like this. ReadWriteLog is an interface and RentrentReadWriteLog is a class.
Which is our basic value and separate our locks so this is our read write lock and this gives us two locks one read lock and one write lock and you know read lock is your shared lock and this is your exclusive lock exclusive ok So now what I'll do is, I'll put a shared lock on read So I can do something like this, first I can write readLock.lock So I've locked it with readLock, which means multiple threads can come in here And here I'll write my try block again What I have to do is, this part, return value And finally I'll release this lock Finally Something like this, and here I can write readLock.unlock Okay Even if we return it, it will still be executed.
Let's make two threads here, I made a thread t1 equal to new thread Not two threads, let's make a dada Obviously I'll have to make an object of sharedResource So first of all, let's say sr equal to new sharedResource Something like this. And what do we do? We say in lambda expression, no input. And you just call sr. I call one read. Okay, so let's assume t1 does our reading. In this way, I make more threads for reading. Let's say this is also reading, this is also reading. So t2 and t3, these are just readers. Now I make three writers in this way. So let's say these are our writers. Okay, so we name it t4. Or let's do one thing, their readers are called R1, R2, R3 And they are called W1, W2, W3 Something like this And they write call of sr So let's say it writes value 5 It writes value 7 And it writes value 9.
So all the threads have started. Now let me tell you what we are expecting. I am expecting that the threads R1, R2, R3 that are calling read, this method, although it has a lock, but it has a lock on it. Shared means that all the reading threads will enter at once, that is, they will stop for a second and do it straight. We are reading the value at once rather than once and the thread of writing will enter one by one in it. So let me run them once. So you can see that all three threads have entered the same way, although they did it in any order, but they all wrote the value.
And after that, these three have rewritten the value. Now if we read it again, we will get the correct value. Although what we have done now is that we have left only one thread in one time. But generally what we do is that we keep looping. We read the value again and again because the value can always change. But majorly you must have understood what is a shared lock and exclusive lock. Since this was shared, all the threads were entered at the same time. And since this was exclusive, only one write lock was entered at a time. If one thread enters at a time, let's say right thread, neither a read thread nor a write thread can enter at that time.
See, what happens is, because our readers, they put our shared lock, And writers write exclusive logs. Exclusive logs which we write in Excel in short. Now, exclusive logs are an overhead, right? Because it is available to one thread at a time. But shared logs are easily available to multiple threads. So, it is more simple. Imagine that you have a shared resource in which multiple readers are coming. So, R1, R2, R3 and so on. And one writer R1 has been sitting for a long time. Now it is possible that these readers will keep coming and they will get a chance to enter because if only one reader enters at a time, then he will put a shared lock in which the other readers will keep entering. R2 also entered, R3 also, R4 also, all of them will enter together, there is no problem. And everyone will keep doing their work. Now R1 reads and then R4 reads, R2, R3, but more readers are coming. The log is not being unlocked because one reader unlocks and the other occupies it. And this is a shared log. So if a lot of readers keep coming, then writers will keep waiting. And there will be a problem with the writer against starvation. So this can happen sometimes. And we call this writer starvation. So we call this specifically writer starvation. And we have to solve this problem. And we have to limit the number of readers we can access together. And the writer too, so that he gets a proper chance. Now again, how do we make this lock? By writing reintrant read write lock. So again, this is also reintrant. That means we can lock one thread multiple times. And we have to unlock it that same time. Which we saw in the reintrant time too. Here, a very interesting concept comes.
Sometimes it happens that you have written something and you have to immediately read what you have written. So what will you do? You will put a write lock. You will immediately downgrade it and add a read lock. But you can't do the opposite. You can't upgrade it. You have a read lock and you have upgraded it to a write lock. You know the simple reason. If there is a read lock, then multiple readers can also enter. So how can we make the shared lock an exclusive lock? But yes, you can make the exclusive a shared lock. How is the simple method of this? Suppose you write such a code. So let's say you had a write lock and you had a read lock.
You locked writeLock.lock Here you wrote some try blocks Let's say you modified the value to 100 So you modified it Now you want to do downgrade So first you will occupy readLock So readLock.lock First occupied readLock After that finally Leave the right lock and unlock the right lock Remember, first we occupy the lock and then leave the old lock Not that we leave the old lock first.
After that we can write finally in our second finally we can write that we have left our readLog so readLog.unlog something like this So this is absolutely allowed in Java that you can downgrade your read write log and this is very interesting, you know why upgrading is not allowed If you understood this then we move on to our third type of log whose name is stamped log stamped log.
So again, this also gives you read-write lock, exclusive lock, shared lock. But it has a little modern version. Now I'll tell you what's more special about it. There are three main methods in it. One is obviously write lock, which will bring you an exclusive lock. One is read lock, which will bring you a shared lock, so that multiple readers can enter. And there is a very interesting method, Try Optimistic Read. Optimistic Read. Something like this. Now this is very interesting. We'll see about this now. First, let's see our normal Read Write Log. It looks like this. There's just a little code change. Now why do we call it stamped? Because it works on Stamps. Stamps are nothing. You can assume that there is a long id. So basically we expect a long stamp. Stamps are nothing but the name of the variable. It will be a long type id. I will tell you how it works. So let's say you will make an object of stamped log. So you will write stamped log log. Equal to new stamped log Now whenever you have to log You will simply write log.readlog But this will return you something The normal read write log didn't return anything This will return you a stamp Long stamp Basically it will return a stamp type id Which you have to store Let's say you have stored it in your stamp variable After that you will do your shared resource work Which you always do Basically the same try work whatever you want to do and finally when you want to break the lock you have the method lock.unlockRead Not just unlock, you have to write unlock read And here you will pass that stamp This stamp that you received here So why do we have to pass stamp here? Simple thing is that Your stamped lock doesn't work like a normal reintrant lock Basically what you did is You gave a thread to an object So basically this thread So basically the lock of this object is occupied by this thread Its owner is this thread There is no thread owner in a stamped lock We give them a stamp in a stamped lock It's like When you go to a parking lot to park your car, you get a token and when you exit from the parking lot, you have to show that token.
When you put a read lock, it gives you a stamp. And when you go to unlock it, you have to pass the same stamp. It finds out that the same thread that had been locked, is it unlocking it? This is just a small difference. Here, stamp doesn't have much benefit in readlock and writelock. But the third method, tryoptimistic read, has a lot of benefit in stamp.
And you have to write unlock write instead of that. And you have to pass a stamp there as well. The same stamp that you read here. So this is their read-write-lock method. Which works the same way as read-write-lock. The name of the method has changed to read-lock-unlock-read, write-lock-unlock-write. They return the stamp to you, read or write-lock. And when you unlock, you have to pass the stamp in the parameter. Now let's see the most interesting thing, the optimistic read.
Before that, let me tell you that in Java, we divide locks in two ways. One is our pessimistic lock and the other is our optimistic lock. We can call them optimistic locking techniques. These are locking techniques, not locks. I can write locking techniques. Now, what does this technique say? Pessimistic is very simple, which we have been studying till now. If you have a critical section, you have to enter it. So, before entering it, lock it and after entering it, unlock it.
Because we are afraid that our critical section can enter multiple threads. So we don't want to take any risk. We first strictly lock it and then unlock it. We don't take any risk with our critical section. Now, One problem with pessimistic lock is that it is slow. Because you must be able to understand that whenever you lock or unlock, you are adding an overhead in your code. Now to lock, you have to go to the lock of that object and you have to make a thread its owner etc. So there is a lot of overhead involved. So Java made a new type of locking technique which is called optimistic locking technique. Now this is fast because actually we are not locking in it.
We are not locking anything here. Now, a very simple thing is that whatever critical section I have, I will enter it in that. Now, this is generally for reading. That's why the method is called tryOptimisticRead. So, I will enter it in that normally. And I will do my reading work. So, I will read whatever my value is. Like I printed system.out.println on the screen. As soon as I read it, I will see if any thread has changed or not. If it hasn't changed, then I will exit from here.
Put a normal lock and read So now I have read the normal optimistic, now I will put the pessimistic locking technique again and read it Now you might not have understood how we found out if our thread has changed or not So here the stamped lock uses the stems Now we will see how it is used. But there are many other logs in Optimistic like CAS. This is also an Optimistic Reading Technique. Apart from this, Atomic Integers. This is also an Optimistic Reading Technique because they are using CAS from inside. We will see this in the next videos. Now let's see how this Try Optimistic Read Stamped works. So here we are going to discuss Try Optimistic Read. And it works like this. First of all, we will get a stamp. Get a stamp.
So read data. Main is here without. Focus on this word. Without locking. Without locking, we will go to read it. Okay. Third. When we are reading, we will check. Checking if data is modified. If it is modified, then we will go to our follower logic that we will read pessimistic again. And if it is not modified, then our work is done. Now let's see how it works in code. So here I have made a file called demo3. java And I have copied the same code which was in demo2. java So basically what I had there I had a read and a write problem which I had declared Which I had solved using my read write lock And here I had made 3 readers and 3 writers and started everything Now let's solve this using stamped locking So first I will make a stamped lock I name it simpleLock equal to new stampedLock So I remove this So here I have a value and a stampedLock whose name is.
I am going to try optimistic read So let's change read later First let's change write which will be simple Here I will do lock.writeLock You know writeLock And I know it gives me a stamp So I have to collect it in a long variable So I will write long stamp equal to something like this so here I have locked it and here is my critical section and finally how do we unlock it? we write lock dot unlock read sorry unlock write and here I will pass the stamp ok so this is my normal stamp it write operation I have locked right and unlocked right and passed the stamp this is very simple now let's go to our read operation so I will not lock it like this and I will not do anything like this.
Lock.tryoptimisticread something like this and this too will return me a stamp so I will take it as longstamp equal to this Now I have written here tryoptimisticread We are trying to read optimistically, actually we are not putting any lock or shared lock here We are just trying to read optimistically Let's remove this code and clean it completely so that we can understand the dance Now I will read the value. So let's say I read a value in the current value. So I read the value stored here in the current value. Now I have to check whether my value has changed in this process. How can I check it? I can check it like this. When I wrote log.tryOptimisticRead, it gave me a stamp. Now what do you do? You wrote int current value equal to value. Now when I did this, I want to check if any other thread has put anything else in this value by right-calling. Now how do we check that? tryoptimisticread gives you a stamp, stamp is an id, it tells you the state of whatever you have written down below. So whatever you have written down below, whether it is a value or a current value, whatever you write, it will become a version of everything in the stamp. Now if someone has changed it to this value using write, So this value will be changed in the variable So the value will be changed here So basically the stamp of this You can consider it as a hash The stamp of this will not match When I will take out the stamp again So here I have a method that I can write If I want to validate my stamp I want.
Will give true that validation is true If my value will not be changed And it will give false if it will be changed So if it is equal to false If it is equal to false If it is equal to false, that means someone has changed the value. That means my validation has failed, my stamp has changed. If it fails, then this is my fall over logic. That now what I will do is try pessimistic read. I will try pessimistic read. And if nothing like this would have happened, if my stamp hadn't changed, then basically in that process I had read the correct value which was my current value.
I can simply print this current value which I was doing earlier, current value. And I can return it. Return current value. Something like this. I was printing something like this, so let's write it here. something like this and here my current value will come and I will write thread.getname reads value to value as ok current value ok so I did this now the follow logic will be exactly the same as what I had written earlier so I can write let's say stamp which is declared above is equal to log.readlog now I have put a proper readlog ok not optimistic now here I will write try try whatever my CurrentValue will have value something like this And finally I will unlock this log So I will write log.unlock I will unlock it and print the current value which I have written here and return it. So I can write a code like this, first I said try optimistic read, if my work is going on then I will not enter in SIF and I will print it straight, that means I have not logged in but if my work is not going on, my stamp has changed, validation has failed, then I will go to my follower logic, then I will read my current value and finally what will I do?
Now after this, if I come back to this line, then I will print whatever I have read and return it. And apart from this, we will add our timer delay of 1 second. Now where will we add it? We will have to add it at the top. Because again, if we add it after validating, our code may change by then. So there is no point in validation. So let's do one thing. As we read the value, after this we enter the validation.
Let's wait for a second and then see how our work goes. We just put a delay of one second. After that, we validate our stamp. If the stamp is validated, then there is no problem, our A will be printed. And if it is not validated for some reason, then we will go to our follower logic, i.e. normal pessimistic read. In which we will put a log and unlock it. Finally, we have to do the same thing, print on the screen and return the value. Now if we run it.
First thread 3 changes value, thread 4 changes value, thread 5 changes value. So you can see, first our writers ran, very good. After that, our reader ran at the same time. No problem, anyone can run first. Writers must have run first because in the starting, here in read, Timer is set to wait and there is no lock here. Before that, there is no lock in optimistic read. We read the value and then set the timer of 1 second. So because all our readers were sleeping for 1 second, the writers changed the value till then. First 5, then overwrite it to 7, then overwrite it to 9 and then everyone.
I hope you understood the logic of optimistic read, how it works. The only thing to focus on here is the method where we write lock.validate and here we pass a stem which can return only two things, obviously boolean, so true and false. Now it returns true when there is no write, our data hasn't changed and it returns false when our data has changed. That means till that time some other writer had updated some values. Now we just have to remember that our stamped log Stamped Lock is not re-intraint meaning you can't lock the same thread in the same object again and again. If you do, you will get a deadlock. Okay, so we have to avoid this in Stamped. Okay, now let's move on to our last topic which was Seema 4.
Now this lock is a little different, behave will be the same But it is a little different, we will discuss that later But now my question is that suppose I have a situation that I want the critical section to enter multiple threads Read write lock just says that multiple readers should enter but only one writer No, here I am saying that all my threads are the same, T1, T2, T3, all are the same But I want multiple to enter And how many to enter, I will tell you the number first 3 to enter, 4 to enter, 5 to enter and so on So we call it SEMA4 and we can control it here. And we control it using permit. So SEMA4 has a count of permits that how many threads it has permitted. So any thread comes, it reduces a permit. You can consider it as a count. So suppose in the beginning the permit was 3, so it said 3 threads can come. So as soon as a thread enters the critical section, it reduces this permit. The second one enters, it reduces it once. If you enter the third one, then it will do 0. After that, the fourth thread will not be able to enter. Until these three threads come out one by one. Now as soon as one thread comes out, our permit will be 1 again. That is, one more thread will be able to enter and so on. Okay, so how do we declare it? We write sema4. Let's make an object s1 equal to new sema4. And here we can pass how many permits are there.
That means we want to allow 3 threads in our critical section. Now obviously some of our methods will come here. Now it's a little different from lock because it's not lock. So our method's name is acquire. So you can write here let's say s1. acquire. They will do the same thing. Like we lock, you know acquire. It will acquire a permit. So from here it will be 3 to 2. As soon as a thread comes here. So I can write this. I can write here take one permit. This takes one permit for us. Okay, if thread.acquire is called and no permit is left, then what will happen if this 3 is zero?
One can be our binary and one can be our counting. Now binary works like a log. So if you write, stima for let's say s1 equal to new And here you pass 1 So it becomes a binary SEMA4 Binary means either it will enter a thread or not It will work like a lock but still it is not a lock And counting what we have seen till now We write SEMA4 S1 equal to new SEMA4 And here we pass a number that how many threads should be entered So now we can distinguish it whether it is binary or counting But actually SEMA4 in general will be different from locks Now I am saying again and again that it will be different from locks Let's understand why What is the difference between this and locks So, I can write lock versus semaphore. Look, there is a very basic difference that our locks are ownership based.
I told you in the beginning that any thread is an owner of a lock. And if a T1 thread has acquired a lock, then no other thread can acquire it. Now the work of releasing it will also be of T1. But there is no ownership in our SEMA 4. I can write here, no ownership. No ownership means that any thread can release permits because here the concept is not of lock but of permits. So for example this is our critical section and here 3 threads were waiting T1, T2, and T3 and here we had put SEMA4 whose value was let's say 2 So let's say one thread enters T1, so it makes this permit 1 and the other thread enters T2, so it makes this permit 0. Now the teacher will not be able to enter, we know that. But when it will be exiting, there is no order here, T1 will just make this permit 1 again and it will exit and T2 will make this permit 2 again and it will exit. Nothing like this will happen that T1 will unlock something because it will own something, it will not own anything. Now see, multiple threads are allowed, so no one owns the lock of this object. There is no parent thread. Everyone is just coming through the permit and going through the permit. There is no ordering or ownership. But there is proper ownership in the lock. One thread is the owner of a lock. Now if you talk about exclusive lock, then there is only one thread, but if you talk about shared lock, then yes, multiple threads are the owner of one lock, but still it is the owner, right? But in SEMA 4, although multiple threads execute, multiple threads enter the critical section, but they do it on the basis of permits.
This is a very simple concept that you have a number count defined, this much thread can come, if that count is zero, then you don't let it come. As soon as a thread exits, you make the count plus plus. This is a very simple concept of SEMA 4. Again, you can also make sema4 fair or non-fair. When you are declaring, when you write sema4 s1 equal to new sema4, then you pass the number of permits you need, and here you pass true. You know, as soon as you pass true, you will make sema4 fair. That is, the thread that came first will get the first chance to enter. Now you think, if SEMA4 is not exactly locked, then where should we use it? And why should we want multiple threads to enter our critical section? There is a very specific use case. Like if you make your own API rate limiter. Then there is a very good use case of SEMA 4 We will see this properly in the Spring Boot application When you make a rate limiter Then what are you doing? You are limiting the number of requests Which should be read on your API Now how many number of requests should come You can define that with SEMA 4 Or whatever parallel task you want to do Parallel task You can limit that. Like I said, I will perform only 5 parallel tasks. After that, I won't perform the 6th one. Until I don't perform any of the 5 tasks, I won't let others enter. We can also use semaphores there.
So this is a very interesting thing. And these are the 4 types of locking mechanisms. Although semaphore itself is not a lock. But it is counted together because we are doing the same thing here. Now, if you understand the final thing, then we have another interface in Java, whose name is condition.
Obviously, it is in a blocked state, but the waiting area, I'm just telling you, there are so many threads waiting here. Now, normally, we have a queue, right? Blocking queue, where all the threads are sitting, if they were waiting for the critical section. This is a little different from that. I'll tell you why now. And every condition is tied up with a lock. So, basically, if I make a lock, log L1 equal to new. Let's make a re-entrant lock. Because re-entrant lock is the most common lock.
I can also create a condition interface, let's say c1 c1 equal to, if I just do it, on this l1 lock, l1 dot is a method, new condition l1 dot new condition, so I will get c1 as a condition, okay, now I can call a method here, I can call c1 dot awaits c1 dot signal call or signal all call, okay Now their meanings are very similar to what you understand. Awaits says that I am asking a thread to go to waiting state. So what will it do? It will release all its locks and go to waiting area. So obviously you know what it does. It releases the lock and goes to waiting area.
But the difference is that the wait, notify, notify all used to have only one waiting queue. But here we are calling these waiting queues conditions. And we can make multiple conditions. That means we can have multiple waiting queues. So, in the last class, we saw the producer-consumer problem. So, we said that we have multiple producers, P1, P2, P3. And multiple consumers, C1, C2, C3. Okay?
If multiple producers and multiple consumers are there, and If there is only one waiting queue, then both the producers and the consumers will come here. But what I can do is, I can make two conditions within the conditions. So let's say I made the condition of the producer and the condition of the consumer. So all the producers will go to the producer's condition and the consumers will go to the consumer's condition.
Okay? I just did nothing, I made the waiting area separate. Now why can I do this? There can be multiple reasons. I want to keep the queue separate because I will signal one of them or make it live. Right? If I had only one waiting queue, which was in this case, and if I would have called notify here, then do you remember what problem we would have faced? One of these threads would have come back, it would have been awake. I don't know if the producer would have been awake or the consumer. But that problem will not come here. Now if I call await on a proper condition, C1, and C1 is nothing, let's assume it is the producer's queue, where all the producers are sitting. So I know that if I make a signal call here, then only one producer.
Again, that's why I said it's modern and better, because it maintains different queues. And the work is the same. Awaits will work like wait. We will ask it to release its locks, go to the waiting state, go to any waiting condition, it will depend on which is its condition, or which is its queue. Signal will revive a queue in a particular condition, so I can write c1. signal. So I'm saying, in the c1 condition, all the threads that I have, awake one of them. And what will signal all do? If I write c1. signalAll, then I am saying that in this condition, unlock all the threads that are there. Again, if you call await signal or signal all on a thread that has not acquired any lock, then again you will get illegal monitor state exception, which also used to come there.
Leaving aside one thing, there can be multiple waiting queues in this, which we call conditions. But there used to be only one waiting queue in this, which we used to call normal waiting queue. So, if we used to call notify in this, then any thread would wake up randomly. But if we call signal in this, then one thread will wake up randomly from that particular queue. Right? So your job here will be to solve the producer-consumer problem that we discussed, with await signal and signal all. And instead of using synchronize, you can use reintrant lock. Because when you use reintrant lock, you can't use them anyway. You will have to call await signal and signal all. This is their modern version.
This used to come in our object class. This Java updated it. So that we can make multiple waiting queues. And what do you do in that? The Wally problem in which we had multiple producers. And multiple consumers. If you don't know what I am talking about. We discussed about it in the last video. Code was also uploaded in GitHub. You can go and see that.
Solve that problem too. Using signal and signal all. Because we have multiple queues. So why do you make producer's queue different? Why do you make consumer's queue different? So now see that you have to use signal all. Instead of signal. Maybe you don't have to use that. Right. Now again, Now again, whether you use wait, notify, notify all or await signal or signal all. Spurious wakeup can happen. Spurious wakeup. And do you know what spurious wakeup is? Even though you call a thread awaits or waits. It doesn't mean that it will remain in waiting state. Sometimes, CPU or operating system can awake them randomly. Although it is very rare. But we have chances. And what do we do to solve spurious wakeup? We discussed this in the last class. We always write our logic in while. Right? We always write our logic in while. So basically if we want to write that our value is not empty, then we will write value is not equal to null. So we will always write this in while. We also discussed this in the last class.
