- Podcasts
- The Java Developers Hub
- Java Multithreading Problems Explained | Race Conditions, Visibility & Instruction Ordering
Java Multithreading Problems Explained | Race Conditions, Visibility & Instruction Ordering
The Java Developers Hub
- December 3, 2026
- 56 min
- Episode 7
About this episodeMultithreading allows Java applications to execute multiple tasks concurrently, improving responsiveness and making better use of…
- Understanding multithreading and concurrent execution in Java.
- What race conditions are and how they occur.
- How multiple threads can access and modify shared resources.
- Understanding data visibility problems between threads.
- Why changes made by one thread may not be immediately visible to another.
- Understanding instruction reordering and its effects.
- Introduction to the Java Memory Model (JMM).
- How shared mutable state creates concurrency problems.
- Introduction to synchronized and the volatile keyword.
- Understanding the happens-before relationship.
- Techniques for preventing common multithreading errors.
- Best practices for writing thread-safe Java applications.
- Java developers learning advanced programming concepts.
- Software engineering students.
- Backend developers building concurrent applications.
- Developers preparing for Java technical interviews.
- Programmers interested in concurrency and parallel processing.
- Anyone working with multithreaded Java applications.
Transcript
From the publisherThis transcript comes from the podcast’s own feed, shown as the publisher wrote it.
Java Multithreading Problems Explained | Race Conditions, Visibility & Instruction Ordering
Yes, so let's start. Welcome back Coder Army to our Java series. And today we are going to see what can be the problems of multi-threading when we write a multi-threading code. How can we solve those problems? What is a synchronized keyword? So we will learn a lot, you will have a lot of fun learning. So, let's go to the screen and start it. So, we are going to see problems with multi-threading. When you write a multi-threaded code, many problems arise. Because think, you are creating multiple threads T1, T2, T3 and so on up to Tn. And if all the threads run parallel or concurrently, then there will be problems. So, today we are going to talk about the problems. First of all, let's say we will talk about the raise condition. What is a raise condition? So, let's discuss about this. Now, race condition is a very simple thing. Race condition says that the final state of your program will depend on which thread was executed earlier and on how much context switching was done. So, basically it will depend on the order of execution of threads. And we know this very well that when we write a multi-threaded code, the order of threads is non-deterministic. So if we have T1, T2, two threads, both are ready, in runnable state, for our CPU time, then it is possible that T2 runs first, then T1 runs, or it is possible that T1 comes first, then T2 comes, etc. There can be a lot of possibilities. And we call our code non-deterministic code. Now let's see the simplest example of this. So let's say I have taken a variable in my code, int count initial value is 0 and I am doing count + + now this line is a very risky line because if we see it for the first time then it will look like this is one statement if any thread executes it then what will it do? it will increase the count value so if count is 0 then let's say t1 thread will execute it then what will it do? it will make count 0 to 1 so it will do the same t2 thread when it comes here it will make count 1 to 2 right? It looks like a very normal statement, but actually this statement is not an atomic statement.
To do this, you need 3 statements or 3 operations. First of all, we will read the count value. Where will we read it? Obviously from memory. So readCountFromMemory. If you want to add count to the memory then you will go to the count memory and read the count from there So this was the first step, in the second step we will increment the count So increment count by 1 And in the third step, once you have incremented the count, you will save the increased count in the memory So I can write that we will write the updated value back So you can see that the operation that we thought was of one step, count + +, is actually not an atomic operation.
Atomic means that we can't further divide this. The basic definition of an atom. I can further divide this count + +. These three operations are performed from inside. So if the CPU has to execute these instructions, then what happens? First of all, you can assume that the CPU will take the count value from the memory and bring it to its own register. It will increase the count by one, i.e. increment it, and will go back and store it in its memory. So let's say, where did I declare this count variable? If I show you a dummy code of it, then let's say we have a class called counter. And let's say there will be only one variable in it, int count.
And we will have only one method, void increment. The one who doesn't do anything, whenever you call this method, it will make this count + +. Now what you can do in your main code, you can make an object of this counter. Let's say you wrote counter c1 equal to new counter. New counter something like this. And whenever you call c1. increment on this c, C1. increment will increment the value of the count from inside. So this is a simple code. If it was written in a single thread environment, there would be no problem. But in a multiple thread environment, there will be a raise condition. Raise condition, which we discussed earlier. What is a raise condition? Because multiple threads will be calling the increment method of our counter C1. So the result will depend on how our threads execute these three operations.
Let me explain it to you properly first, then we will go to the code and see. Imagine this was our code and suppose there are two threads in our code T1 thread and T2 thread which are running simultaneously Basically both will be in runnable state, the one who gets the CPU time will run Now it may be running parallel, exactly parallel It may be running concurrently, we don't know We just know that both are in runnable state and both are ready to run That means the output can be non-deterministic And what we did on both, we called the increment method So I will explain to you what is the race condition Before that, you just have to remember these three steps, that count + + actually means these three steps, that we read the count values, increment them, and then write them back in our memory, from where we read them.
So, let's say, what happens, that our t1 thread and our t2 thread, both reach inside this increment method, right, simultaneously. That means, both of them will reach this count + + simultaneously. Now, see, what will happen? What I do, so see, here I write steps, okay, which can happen, Here we will write about t1 and here we will write about t2.
So now concurrently also assume that first t1 thread enters inside this increment. So it will see count + +. Now I told you that count + + is not a single statement. It is made up of three statements. That we first read the value, update that value and then write it. So assume at this step it has read the values of count. and read the initial value of the count. In that case, T2 thread did nothing. Suppose it was not running, it was in runnable. In running state, there was only T1 thread. Now comes step number 2. As soon as step number 2 comes, it has read it. But suppose contact switching is done. Our T1 thread went out of CPU time. And in that case, T2 got its CPU time. And now it will go and start executing our increment method. So in step 2, it will also see the statement. Now T2 thread came here. So what will it do in step 2? It will also do the first step in this count + +. Which was readCountFromMemory. So it will read the initial value of the count. That means it will also read count equal to 0. Which is the initial value of count. Both of them haven't incremented yet. Okay, after that it also did context switching. Now again, on step 3, it will do context switching of t2 and t1 came back to execute.
So the first step was readC equal to 0, now we have to do the second step which is increment the value of this count. So what it will do is increase this count to C plus 1 and again its context switching will happen. So suppose the context switching is happening after 1, I am just explaining you how this condition will come. Now it will do the same thing, T2 will come, we have read it, now we just have to increase C to 1, so it also increases it to 1. Now let's assume that it has also been context switched. Then what will happen in the 5th step? T1 will come back, it has read, it has incremented, now it will save it in the memory. So what did it read? It read 0, which means it must have incremented 1 here. It must have increased 0 to 1, so it must have become 1. So what will it try to store in the memory again? So it will basically try to write 1. Let's assume it's context switching again. Now we have 6th step. Now T2 is running again. What will it do? It has read and incremented. It also read 0 and incremented 1. That means it will also try to write 1 in memory. So you see, logically what should have happened is that 2 threads were executing this count + +. So actually 2 threads were executed from this 0 count.
First, one thread would have taken 1 from 0 and the other one would have taken 2 from 1. But what actually happened? Finally, in the output too, we only had 1 stored in the count. It must have overrided it. So finally the value of the counter is 1, although 2 threads T1 and T2 together executed it.
That while doing these 3 operations, the context switching happens in between. Like the first one read, T1 read, it came out of its CPU time and went to read T2. So T1, T2 both have read 0, 0. And this is the problem. So this is why we have race conditions. This is very common. And as a developer, our role is to write a code so that race conditions don't arrive. Because it can introduce a lot of critical bugs in your programming. Now you are thinking, this is concurrently, we have understood. It is running parallelly. If it is running parallelly, then also you think, let's say both try to read together, then also it can happen that both.
Now we will see later how to save the race condition. First let's see the code of this. So here I have taken a project by doing demo.java. So what I do is first I make a class which I had said counter. And nothing will happen in this. There will be only one count variable int count. Which is initially zero.
So now what I will do in this lambda. I will try to increment this thread. Now if I increment once. Let's say I can write here. That I will not take any input. Before that I work. First of all I make an object of this counter. So counter C1 equal to new counter. And I will not take any input here, I will just increment C1. Like this. And let's say I will make a T2 thread, I will increment T2. I am writing t2Thread and it will also do c1. increment. So I am expecting that sometimes the raise condition will come and the final value of the counter will be 1 instead of 2.
So there is a very high chance that there will be 2 prints, very less chance that there will be 1 print. So there are 2 prints again and again. So we will feel that our code is working perfectly. But I will try to bring the raise condition. So what can I do for that? I will put a loop here. Let's say for int i equal to 0 or let's run it from 1. i less than equal to let's say 10,000. So I will increment the count 10,000 times, every time I call c1. increment So I will increment the count 10,000 times with t1 and I will increment the count.
Increment and I will wait for t1 and t2 to join and finally print c1. count Now, my expectation is that my result should be 20,000. If I think from the first thought principle, if there is no rate condition in both the threads, then this will count 10,000 times and this will count 10,000 times. So, my final output should be 20,000. But there is a good chance that my output will be less than 20,000. And why will it be less? We just saw that on the iPad. So basically, if there is a race condition, sometimes between two counts, that one has read, then that contact has been switched, then the other has read the same value. So our total score can be a little less than 20,000. How many times can this happen? Now, the more times it happens, the lower our score will be. So let me run it once and Our total score was 12,109. We were expecting 20,000. But the interesting thing is that if I run it again and again, then my total score will keep changing.
Right? In our code, that risky area is this method. The code inside this, count + +. This is critical section. Why is it critical section? Because look, our counter has only one object which is C1. And C1 has both threads, T1, T2, both. and both are calling its increment method. So there is a very high chance that both C1 and C2 threads will enter in this increment method. In that case, we will have a raise condition. So we call this area which we have to protect as our critical section.
If I call this critical section. Then the actual resource which is being shared in all my threads. I call that shared resource. Shared resource. And what is our shared resource in this code? Our shared resource is this, count + +. This is a shared resource. Because multiple threads, t1, t2, share it with each other. Now our shared.
Or let's say you have made an object, let's say a bank account type, you have made an object called account. So it is possible that in that case, your account is a shared resource. So shared resource can be anything that lies in the critical section and multiple threads are sharing it with each other, sharing that resource with each other.
I had told you that whenever I write count + + on the screen, it is not a single operation. Rather, it is made up of three small operations. In which we first read the count, you know. then we update it by one or I can write it increment by one increment by one and then write our count back to memory. So where does the count go back to our memory? Okay, so these are the three steps when we write count + +. And in Java, we define a term which we call atomicity. Right. Basically, I say in Java, any operation will either be atomic Atomic or non-atomic. What does it mean? Atomic means that it is a singular operation. I can't further divide it. Either the operation will be successful or it will be a failure.
Thread t1 reaches here, it reads, but its context switching happens and t2 returns Now, if t2 comes, then it will also read the old value and its context switching will also happen. So, the problem we were facing, context switching was happening in one count + + because it is further divided in multiple operations. It was happening because our count + + is a non-atomic operation.
So, if I write its definition, then in Java, we give its definition as such that any operation that either happens completely or not at all, either it will be successful or it will be a failure. It will not have any half way or mid way. Okay, as an example, if you take any one of these operations, read count or increment by one or write count, these three are atomic operations. To read any value from memory is an atomic operation. To increase any value from one is an atomic operation. So basically, if I write that I have written this statement, then this is an atomic operation in itself. To do this operation, I don't have to divide further into some other operations. So it doesn't matter how many threads I have, whether it is t1 or t2, t1 will also do x equal to 0 in one go, t2 will also do x equal to 0 in one go. Meaning, without switching the context, either it will do this work or not, or before this. It means either contact switching will happen before this or after this work. It will never happen that while doing this, our T1 thread's contact switching happened. I hope you got the idea of what atomic operations are. You can only believe that any operation which any thread.
So let's say if T1 was executing this operation, then either it will get context switched here before doing it, or after doing it straight, it will get context switched here. But during that process, it can't happen because it is such a small operation that either it will complete it or not.
Like it can't happen that you are reading x with memory, so you read half of it. Now you read half of x and didn't read half of it, right? Nothing like that can happen. So we call that atomic operation and non-atomic operation. And you can understand that the raise condition in count + + was coming because this operation was non-atomic. It was divided into three parts. Because of this, any of our thread T1 would get context switched by reading it and the other thread would also read the old value. Now let me tell you how much the problem of atomicity can affect us in real life. Let's say you are making a banking application in which you have two accounts.
And what you have to do is you have to make a debit and credit facility. You know what happens in debit and credit? Let's say from account A to account B, you have to pay 500 rupees. Debit will happen. So basically, what will account A do? He will try to send Rs. 500 to account B. But now think, if I don't make this whole operation atomic, then I may face some problems. Now look, normally think, how will this operation happen? It will happen like this, that account A will have some balance, and account B will also have some balance, right?
Now, if I don't make this whole operation atomic, then one of my threads would have reduced Rs. 500 from account A. But it gets context switched. That means, account B never gets its money. And let's say, when it gets context switched, whatever the name of the thread T1 is, let's say, after that, it couldn't run because of any reason.
Right? Or it might have gone into a waiting state. And it's waiting infinitely for a long time. So, if money is deducted from account A, but money is not received from account B, then this is very problematic. This banking application will not work for you. If you have done UPI of 500 rupees, then money is deducted from your account, but it is not received.
Because it is a non-atomic operation to reduce the balance from here to here. Because it will take multiple steps to make the computer, to make the CPU. We will come and see about this, what are the ways to make this statement completely atomic. We use some internally CAS theorem, which we will see in the next videos. But I hope you got the idea that the problem of atomicity is so big in multi-threading. Now, if we solved this problem of atomicity, then we solved the problem of race condition as well. The race condition of count + + that we were getting, we would have solved that as well. So generally, we have two ways to solve this problem. One is synchronized block.
So first of all I will write the operations which will always be atomic. So for example, any simple assignment operator. So you have written int x equal to 2. This is our atomic operation. Why is this a simple atomic operation? Because what are you doing here? You are saying to store 2 in an x block. It is a simple write operation. You are just doing a write in memory. Now how will you further divide it? How can you do half write? So this is an atomic operation in itself. Apart from this, any reference assignment, let's say you make an object of student, student s1 equal to new student, this is also an atomic operation. This whole thing happens in one go, you can't further divide it. Because what are you actually doing in this? You make a student object in heap memory, whose address you keep in reference variable named s1, which is in the stack, right? So this is also an atomic operation in itself. Okay, so now if I ask you which is non-atomic, now it will be easy for you. Any such operation like x + +, y-minus, increment, decrement operators. These are all non-atomic because you know how to operate from inside. Because you know how to divide from inside further in three operations. Or apart from this, you can take any compounded statement that I am writing x equal to x plus 5. So, actually what I am doing is, first I will fetch x from memory, increment 5 in it and then I will.
Whenever you perform a task in which you check first and then perform the action, it becomes non-atomic by default. So let's say in this example, in which we had to reduce money from the account and increase it here. If I had implemented it, let's say I write something like this, let's say I write the balance on the same side of the account, if it is more than zero, Then only withdraw from the account. Balance minus whatever amount you have to give. Let's say AMT amount. Then only withdraw. And obviously here one more check should be applied. Greater than zero. Greater than amount. Greater than equal to amount. So if your balance. Your account's balance. Is more than 500 or equal to it. Then only you can give 500 to someone. So here I have applied that check. Balance minus amount. So basically what I am doing. First I am checking something. Then I am performing an action. So whenever I check something and then act, it will always be non-atomic. Because obviously, if my thread executed this line, then it will come inside this if, but as soon as it comes inside if, its context will switch and it will go out again. Now this problematic happens because of check then act. Suppose you had two threads, T1 and T2, which were trying to execute this line.
And T1 wants to deduct 500 rupees and T2 wants to deduct 600 rupees from the led. Something like this. So suppose T1 comes and executes this line That balance is greater than or equal to amount So T1 has to withdraw 500 rupees So he will see that 1000 rupees is more than 500 rupees That means I can withdraw 500 rupees from the user So it went to our inner line Which is balance minus amount Now here is the problem As soon as it starts executing this line We did context switch to T1 So T1 went to wait Now came T2 Now where will T2 come? Obviously T2 will come back to this if line So T2 will also check if my balance amount The balance is 1000 and how much do we have to deduct from it?
Suppose this was a second transaction. So that too came into it. Now when it came into it, suppose that too did not switch the context. So what will it do? It will minus this amount from this balance. So basically from my balance, which is 1000 rupees, I will minus 600 rupees and I will have 400 rupees left. I have only 400 rupees left. Now when this statement is executed, my if block is finished. Now my T2 is a contact switch. Now my T1 is back. So when T1 comes back, it will enter in this line. But logically, did it have to enter in this line? The answer is no. Because now this condition has failed. Which is balance greater than equal to amount. Because my balance is only Rs.
If your bank account has only 1000 rupees, then you cannot do this 1100 rupees UPI, right? Even if you do it in two transactions. that you sent your cake for 600 and then you sent 500 to someone else. But if in this case we didn't handle the atomicity properly, then this problem can arise here. I hope you got the idea of how big the issue of atomicity is in real life scenarios. Now I'll tell you an interesting thing. This is definitely the case in any compiler. If you declare a double in your code, let's say double D equal to, let's say 112.234, something like this. In that case, you might think that it is atomic because we are actually writing a value. But sometimes JVM does this in two operations. Because you know that 64-bit is doubled. And sometimes our JVM writes in two parts of 32-bit. That is, 32-bit once and then 32-bit twice. It writes memory in two parts of 32-bit. 32 bits, that means this operation is non-atomic. There can be a raise condition here, another threat may come and write something else here. Or write something else at the back. So our entire variable will be stored wrong. So in that case, just remember that this is a little edge case. So if you store something double because it is 64 bit, then what do many GBMs do? They store 32 bit by 32 bit. In that case, our atomic operation does not remain. Okay, if you understood this problem, then let's talk about the next problem in our multi-threading, which is the problem of visibility.
I first write the definition of this, then it says that suppose you have two threads, thread1 and thread2 and one thread updates a variable, so one thread updates a variable but the other thread does not see the updated value, it has not seen the updated value, that is, it became invisible for it. This is called the visibility problem, that we have two threads, t1 and t2. Let's say T1 has updated a count and it has set it to 1 But when T2 reads it, it might be 0, meaning it is reading the value of the previous count I'll tell you why this happens, but this can also be a problem in multi-threaded code Now let's see why this issue occurs First of all, imagine that you have a CPU of 2 cores So it should have 2 cores, so let's make it like this, 1 core is this, CPU is this, and 1 is this So basically we have two cores that can simultaneously execute two threads. Now these two CPUs have their own registers in which they store intermediate values. So they combine and make a CPU. So I am ignoring it now. You can assume that CPUs have their own registers. So you can assume that they are internal. They have registers inside them. But after that, we have a layer which we call cache layer. Now that cache layer is also in multiple levels. L1 cache, L2 cache. But for now, you simply assume that this CPU has its own cache. Same, this CPU has its own cache. Now, there are multiple levels of cache, but I'm just making one in my mind. After that, the cache memory is connected to our RAM memory. So, this is some structure. We must have studied this in the operating system. So basically we had two cores, cache and a major RAM where we store our variables. Our stack space, program counter, heap space and method area are all stored here. So everything is stored here. But because CPU has to do processing, and our RAM is very slow, cache is very fast, and its registers are faster than the cache, so it stores some results in its register, and some results in its cache.
So suppose you have a variable, flag and that is false flag equal to false so obviously it will be stored in our ram now suppose there are two threads one is t1 thread which is executed in cpu1 and the other is t2 thread which is executed in core2 so it is possible that this t1 thread read this flag equal to false.
So T2 also read flag = false, and it brought it to its cache flag = false, sorry, it read flag = false, I wrote true here, okay, false, and both of them brought it to their cache. Now let's assume that our T1 changes the value of this flag, so flag = false, makes it true, okay, and as soon as it does true, it will update it back to the RAM, right? So it did true, and here it updated to the RAM, so it became true in the RAM too. But T2 doesn't read from RAM, because the flag value is there in the cache, so it always reads false. And the new value of the flag is not visible. So what happened for this? The new value of the flag became invisible. This is called the visibility issue. So the final value of the flag for T2 thread became invisible. It is only reading its old value. So this is also a big issue. Now this never comes in a single thread. Because obviously, if T2 doesn't exist, then it would have read it. Like it would have read it false, updated it as true and would have stored it back. Even if it didn't store it, it would have kept it in its cache and kept updating it there. So basically, if there was only one thread, then how would it play with this flag? Whether it is picked up from RAM or cache, it will always get consistent value. But the problem arises when we have two threads or multiple threads. Because now see here T1 has made the flag true. But for T2, the value of the flag is still false. And because of this, many issues are included. So see, to show the problem of visibility, I have made a file by doing demo.troddler.java. So let's say we do the same example we saw. We make a Boolean variable first. Let's say I made a Boolean. Lag was initially false. Now I'll make two threads. Let's say I made a T1 thread. Equal to new thread. And I'll make a T2 thread. T2 equal to new thread. I'll write the logic in both. And then I'll start these two threads.
What I'm saying is that this T to thread will run infinitely. It won't take anything in the input. And what will it give in the output? It will do this while, until the flag is not true, until the flag is false, it will keep running infinitely. And let's say it will keep printing something on the screen. And it will print thread to running. Until flag's value is not true, it will keep printing thread to running. Currently flag's value is false, so obviously this is our infinite loop. It should work until flag's value is not explicitly true. So I'll do one thing, t2 will keep running until flag is not true. t1 will make flag true. How will it do that? Again it won't take anything in input. What will it do in output? Either I'll make flag true directly, but let's do one thing, let's take a 1 second sleep. So I will first do thread.sleep so that a lot of thread to running will be printed for a second. I have made this thread sleep. Now it will throw an exception. So let's say I catch it in exception E and leave it empty. I have to give time here. So let's say I made it sleep 1000 milliseconds, that is, I made my thread T1 sleep for just a second. So, while thread T1 is sleeping, T2 will be running continuously because flag's value is initially false. So, thread 2 running, thread 2 running, thread 2 running will be printed on the screen. Because I have started both. Now, as soon as thread 1 comes back, it's okay. So, it will see that my work is over. As soon as it finishes its work, it will set our flag variable as true.
So if there is no issue of visibility, then what is my first thought principle? What should be printed on the screen? Since both the threads have started, T1 will go to sleep as soon as it starts, but T2 will start printing thread to running continuously. So it will print a lot of thread to running for 1 second, because the flag's value is initially false. But as soon as the thread comes out of T1 sleep, it will make this flag true.
If I think from the first thought principle, then as soon as the flag is true, This while loop should end because the flag is now true So thread2 should come out of this while loop and stop And let's print it here Thread2 finished So many thread2 running will be printed and after a second thread2 finished.
Thread to finished. But you said that it won't stop. How did it stop? Let me tell you what happened. In this infinite loop, there is a system.out.println, a printing statement is written. Internally, this printing statement is by default synchronized. We will see what is the meaning of synchronized and how it is made. What happens because it is synchronized? It doesn't read our value with its cache. It reads it directly in the RAM.
Right? Why? Because the printing statement we have written system.out.println it synchronizes our entire block. Okay? So I don't want this to happen. So I will do one thing. I will comment this line. So, I'll do this line as comment. I don't want to print anything here. Basically, I want to do nothing here. So, I assume that thread2 won't do anything. So, after a second, thread2 should print finished. And by that time, nothing should be printed. Right?
Now, if I run this code, So now my code is not stopping for 1, 2, 3 seconds. My code will not stop here because now I have the same problem which I told you about. My thread 2 is reading the value of this flag with its cache. Because as it did while not flag, it must have stored this flag in its cache So what is the condition? While flag is false. What does not flag mean? You can write it like this too. As long as flag's value is false, flag is equal equal false. You can write this too. This is just an equivalent statement. So when you have written here, while flag equal equal false, so if you want to compare flag, if you want to compare flag to CPU, then you have to take the flag variable from RAM and bring it to your cache. So thread2 brought it to its cache. So let's say in thread2' s cache, we wrote flag is equal to false. is equal to false. Now thread1 has made the flag true from the back. So thread1 did this true in its own cache. So in thread1' s own cache, it made the flag true. Now if there is a right operation in the cache then by default it should also go to the RAM. This is the rule of the operating system. So this flag equal to true will actually be removed from the cache and put here as well.
Right? So this becomes an issue of our visibility Because our T2 will keep on reading the value of flag with its cache Because it will think that this is the source of truth It doesn't know that another thread will change from the back But thread 1 has changed from the back And it has changed in its cache And if something is right in the cache then by default it goes to the RAM So it is true in the RAM as well But who will tell that to T2 To avoid this case we have a keyword called volatile What if I use here.
So I have declared here static volatile boolean. Now if I run it, then the problem should be solved. See, our thread to finish has been printed. That means it didn't go in the infinite loop. Why did the problem get solved with volatile? So see, what happens with volatile if I tell you. Volatile keyword just says that this variable flag, whenever whoever will read it, any score will try to read it, then it will always read with RAM, it will not read with its cache. So now whenever thread1 and thread2 need a flag, they won't read it with cache or write it in cache. They will perform read and write directly in RAM. So in this case, when thread1 did flag = true, it stored it directly in RAM. And in this case, when thread2 puts a loop while flag = false, it is comparing the flag with the RAM again and again. So after a second, the flag will be true in the RAM. And it will be visible because it will come from the RAM. So flag = true, it will come out of the loop and our thread2 will be printed as finished. I hope you have understood what is the problem of visibility and how we can solve it. Just remember a normal volatile keyword. Volatile is a very useful keyword. Like I told you about synchronized keyword. Which solves your atomicity or race condition problem. Volatile solves your visibility problem. Just remember this volatile keyword. It doesn't solve race condition. It has nothing to do with race condition. So if you write this in your old code.
Count equal to 0 and then do count plus plus and you think now there will be no raise condition in this count so you are absolutely wrong. It is just saying that whenever you read this count, read it with RAM. But the raise condition was not coming because you were reading from the wrong place. The raise condition was coming because multiple threads were going to execute it together.
Because this operation is made up of three operations, the context switching used to happen between them. Visibility is a completely different problem, which I have just explained to you with an example. And this volatile keyword removes it. Now, an interesting thing. If you don't want to apply volatile, then our synchronized keyword will also solve this visibility problem. But since we haven't understood about synchronize yet, we'll see that later. Now, synchronize works on locking mechanism. Locking mechanism locks the area of critical section and lets one thread come in at a time. And when that thread comes out, another thread comes in. Whenever lock is released or unreleased, all our cache memory, it gets flushed out and the read is always back to RAM. We will see about this properly. For now, let's assume that you use volatile or synchronized, both can solve our visibility problem. Generally, we prefer volatile because it is based on synchronized locking mechanism. We specifically reserve it to solve the race condition. But yes, as I told you from the inside, if you were using println, then also our thing would get synchronized because println uses synchronized keyword from inside and in that case we know what happens if it uses synchronized it means it uses locking mechanism and locking mechanism means we flush out our cache and we start taking all our things back from RAM the same thing which is basically doing volatile just one more step that it uses locking mechanism if we read synchronized properly then we will understand it better now let's move towards our next problem which can come in our multi-threaded code which is ordering Ordering. Now, what is the problem of ordering? Look, ordering says the sequence in which instructions are executed.
Look. Imagine that you have two variables in your code, one int a and one int b. So let's say you do int a equal to 1 and let's say you do int b equal to 1. Till now we had understood that our flow of control works like this. So it comes by executing things from top to bottom and left to right. So after seeing this code, what comes to my mind? First of all, Java will see this line. So it will say that we have to make a memory. whose name will be A, integer type and it will have value 1 and after that it will go to execute another line basically it will make a memory B and it should have value 2, this is also integer type so first it will execute this line and after that it will execute this line till now we knew this but here comes JVM's optimization And here comes the bitter truth that it is not necessary that these two statements are executed one after the other. It is possible that first int b is equal to 2 and then int a is equal to 1. Why will this happen? Because JVM does a lot of optimizations from inside. So basically from inside, because of our compiler optimization, Or our CPU can also reorder these statements so that it can run them efficiently.
There can be many more reasons, if we go into depth, then you can understand it like this. Because the CPU may feel that doing this statement first and then doing this statement is more optimized. Our compiler may feel that we can do this first and then do that. Now because the compiler of Java is written in such a way that it further optimizes itself, So, we always think that the instructions are executed line by line. This is not the case. It is possible that this instruction is executed first and then this one. Because of that, we can have an ordering problem in multi-threading. But think, if Java knows that there is an ordering problem, then why did it do this? It would have been on the basic principle that things will be executed line by line. Because look, Java didn't make any useless rule like this. It said that whatever reordering I do, it will make sure that if your code runs in a single thread environment, then there is no problem.
Those things which don't change any sense by reordering. So even if you declare B first and then A, there won't be any problem in your code. So maybe they will reorder it. I am not saying that by sure they will do it. But maybe they will reorder it. But suppose your B variable is dependent on A. You write int B equal to A plus 1. So it is obvious that first it will have to declare A and then B. If it will come to do B first, In this case, if it goes to B first, then it won't get A, or there will be an error. So, compiler will only optimize those things or perform the same reordering, where your single threaded code can run properly. Now, why didn't it promise to run multiple threaded code properly? Because multiple threaded code is non-deterministic. JVM or compiler doesn't even know what problems can arise in running multi-threaded code.
So in multi-threaded code, because of re-ordering, there is a problem. That problem is called problems of ordering. Let's see how it can be solved. So if I tell you a problem, let's say we declare two variables in our code. We declare int x equal to 0. And let's say we declare a boolean variable, boolean flag equal to false. We declare these two variables in our code somewhere. Now suppose I have a thread 1 in the code. I have written the code like this. Internally, it turns this x to 10 and this flag to true. Similarly, I have another thread, thread 2, which writes a condition that if flag is equal to true, print, let's say system.out.println, let's say x, print the value of x. And then what do we do in our code? So you know what I have done. This part of the code will be in the run method and you will pass it in lambda. So now you will see what answer you are expecting. You will expect that if thread1 goes first, then it will make x equal to 10. So basically I will have an x variable in which 0 was stored and a flag variable. It was stored as false So if t1 runs earlier, then it would have made this x 10 And flag would have been true Right? Now as soon as flag is true So basically this condition can work Before that thread 2 couldn't work Right? Now as soon as I came to thread 2 and saw if flag is equal to true The answer is yes You will print x Which means you will print 10 on the screen You are expecting something But it is possible that your output will be.
Because it is possible that our thread 1 reorder these two statements. Means first execute this statement and then execute this statement. So now think, if he executed this statement first, then what would he have done? He would have made this flag false or true. And as soon as he goes to execute the second statement, his contact switch will be done and t1 will come out. Means its value will remain 0. So basically its value will remain 0. It will remain 0. It will not be able to update to 10. But our flag will be true from call. Now suppose thread 2 has come to run. So it checked if flag is equal to true.
There can be many more scenarios. It is possible that thread 2 runs first. So by default flag was false. So flag is equal to true and the answer is no. It will come out from here and there will be no print on the screen. There will be no xprint. There can be multiple scenarios in multi-threaded code.
It depends on the probability that it can be recreated or not. That's why our multithreaded code has to handle a lot of edge cases so that there is no problem like ordering, visibility, race condition, or atomicity. So that no problem is introduced in our code due to multithreading. Again, there are only two ways to solve this problem. Either we use synchronized keyword.
You don't reordering using synchronized keyword. Again, it uses locks from inside. Or you declare your variable as volatile. You say this is also volatile, this is also volatile. Because volatile variables don't reorder. So basically, I can say that the volatile one will ensure reordering as well as visibility. But it can't ensure atomicity. It can ensure synchronized as well. So if you understood all this, then you will easily understand this term means thread interference. What is thread interference? So till now what we were reading was thread interference. That we have multiple threads like T1, T2 and both of them are troubling each other's work. So, it's possible that it executes some critical resource. So, T1 changes something in it. T2 gets a visibility problem. Or race condition.
These are all problems due to which thread interference occurs. And because of thread interference, the inconsistency of data is introduced in our code. which is the most dangerous thing, right? You write your entire code or application for your data, right? Data is the most important for you. If you are making a banking application, what will be the data in it? Let's say user's bank account, right? Balance in his account, information of your users, all this is data for you. Every application, every code that you build, you build around the data only. If your data is inconsistent, then you think how many problems will be introduced, right? And we have solutions for these problems. For example, we can use synchronized blocks, which we will see later. We can use volatile keywords, we have seen this too. Apart from this, there are our atomic integers, we will discuss about this too. Or we also have other locking mechanism, proper locking mechanism. We can use that too. And in our upcoming videos, we will understand about all these things.
You must have learned that how many problems can be solved by writing a multithreaded code. So, we have a lot of edge cases and our job as a developer is to handle all those cases. Now, in the next video, we will discuss how we can protect them by using synchronized or atomic integers. We will meet you in the next video.
