Podcast Lookup

Java Multithreading Problems Explained | Race Conditions, Visibility & Instruction Ordering

The Java Developers Hub

  • December 3, 2026
  • 56 min
  • Episode 7
Episode page
About this episodeMultithreading allows Java applications to execute multiple tasks concurrently, improving responsiveness and making better use of…
Multithreading allows Java applications to execute multiple tasks concurrently, improving responsiveness and making better use of available system resources. However, working with multiple threads introduces challenges that can lead to unexpected application behaviour and difficult-to-debug errors.In this episode, we explore three critical problems in Java multithreading: race conditions, visibility problems, and instruction reordering.You'll learn how concurrent threads interact with shared data, why one thread may not immediately see changes made by another, and how the Java Memory Model influences the execution of multithreaded programs.Whether you're learning advanced Java or preparing for professional software engineering, understanding these concepts is essential for writing reliable and thread-safe applications.What You'll Learn
  • 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.

Who Should Watch?
  • 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 publisher

This transcript comes from the podcast’s own feed, shown as the publisher wrote it.

Java Multithreading Problems Explained | Race Conditions, Visibility & Instruction Ordering

00:00—
  1. Speaker 1

    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.

  2. Speaker 2

    CPU doesn't consider it as a single statement.

  3. Speaker 1

    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.

  4. Speaker 2

    Atomic doesn't mean anything.

  5. Speaker 1

    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.

  6. Speaker 2

    Int count, which will initially be 0.

  7. Speaker 1

    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.

  8. Speaker 2

    Or in which order they execute. Okay?

  9. Speaker 1

    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.

  10. Speaker 2

    Okay? Okay.

  11. Speaker 1

    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.

  12. Speaker 2

    Something like this. So let's say what will happen in step 1.

  13. Speaker 1

    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.

  14. Speaker 2

    So read....

  15. Speaker 1

    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.

  16. Speaker 2

    We should have gone to 2.

  17. Speaker 1

    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.

  18. Speaker 2

    This is called race condition, right?

  19. Speaker 1

    Because count is not a single statement, it is made up of 3 statements in which we read the value once, update it the second time and write it the third time.

  20. Speaker 2

    So it is possible.

  21. Speaker 1

    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.

  22. Speaker 2

    Now imagine that both are running parallel.

  23. Speaker 1

    So in step 1, T1 and T2 are running on different CPUs and cores. So T1 and T2 are running here. What will both do? Both will try to read the value of the count. Even then both will read equal to zero. This will read equal to zero and this will read.

  24. Speaker 2

    Equal to zero.

  25. Speaker 1

    Because both are running concurrently. Both will hit the initial value of the count on this read operation. Both of them will get 0, 0.

  26. Speaker 2

    Right?

  27. Speaker 1

    So, both of them should be running parallel. Both of them will read 0, 0. Both of them will update it 1, 1. And both of them will basically save it. 1, 1 will save it.

  28. Speaker 2

    Again, the same problem came. Right?

  29. Speaker 1

    So, I am saying that multi-threaded code is non-deterministic due to which our race condition can arrive.

  30. Speaker 2

    Race condition. Okay?

  31. Speaker 1

    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.

  32. Speaker 2

    Simple. Okay.

  33. Speaker 1

    So let's make it of public type so that we can directly access it. public int count equal to zero. And I keep the same method in it. Let's say void increment.

  34. Speaker 2

    Increment.

  35. Speaker 1

    The one who doesn't do anything will do this count plus plus. This is what I said.

  36. Speaker 2

    Okay.

  37. Speaker 1

    So now what I was saying. Now here I make two threads. So let's say I made a T1 thread equal to new thread. You know here I write new thread.

  38. Speaker 2

    Okay. And here I pass a lambda.

  39. Speaker 1

    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.

  40. Speaker 2

    So basically I will start these two. I have started t1. start and let's say I have started t2. start.

  41. Speaker 1

    And when both t1 and t2 are finished, I have printed c1.

  42. Speaker 2

    Count in my main code.

  43. Speaker 1

    Now I will do one more thing. I have started them and I have directly printed c1. count on my main thread. So I told you that it takes time to start. We will ask the operating system to make a thread. So it will make two threads, t1 and t2, it will give it stack space, it will.

  44. Speaker 2

    Get program counter space etc. it will be executed in the same time.

  45. Speaker 1

    So there is a very high chance that our count value will be printed as 0 or 1. So let's do one thing, after writing these two, I.

  46. Speaker 2

    Will write t1. join and t2. join.

  47. Speaker 1

    So basically what I am doing is that I will stop my main method until these two finish their work. Now obviously you know that join gives you an exception.

  48. Speaker 2

    So let's throw it here. Interrupted exception. Interrupted exception. Okay. So, I'll do this.

  49. Speaker 1

    So that my main thread stays. Meaning, I won't execute this statement until T1 and T2 finish their work. And both of them terminate. So, now if I execute this code. So, if I execute this code. So, there will be a very high chance that my C1. count will be 2 printed.

  50. Speaker 2

    Right?

  51. Speaker 1

    Because I'm doing each operation here. I'm doing each increment. Now, in each increment, race condition is less likely.

  52. Speaker 2

    Right? I'll have to increase its chance. But first, I'll increment. See, 2 printed.

  53. Speaker 1

    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.

  54. Speaker 2

    10,000 times with c1.

  55. Speaker 1

    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.

  56. Speaker 2

    This time it was 19,669.

  57. Speaker 1

    That means there were very few race conditions. Now let's assume I run it for the third time. This time it was 11,864. That means there were many.

  58. Speaker 2

    Times race conditions.

  59. Speaker 1

    So you can understand what race conditions are and how they affect our program.

  60. Speaker 2

    Now look, we....

  61. Speaker 1

    If we talk about the race condition, then you should understand one more thing. What is critical section? Critical section. We had discussed this before. Critical section is that area of your program which multiple threads are sharing with each other.

  62. Speaker 2

    And that is a risky area.

  63. Speaker 1

    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.

  64. Speaker 2

    Now see, there is another interesting term.

  65. Speaker 1

    I had said that my method void increment It was written like this. What I used to do in it? I used to just count plus plus. Count plus plus.

  66. Speaker 2

    Okay.

  67. Speaker 1

    So I said that this part of our increment method. Of our counter class. I call this critical section. Because it is shared in our multiple threads.

  68. Speaker 2

    Okay.

  69. Speaker 1

    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.

  70. Speaker 2

    Resource can be anything.

  71. Speaker 1

    Let's say you have made a list in the critical section. It can be a list of integer.

  72. Speaker 2

    It can be a shared resource. Multiple threads share it.

  73. Speaker 1

    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.

  74. Speaker 2

    Okay.

  75. Speaker 1

    If you understand race condition, critical section and shared resource terms a little, then you will understand very well. Problem of atomicity. This is the second problem. Atomicity problem. In fact, our race condition in count + +, its root cause was atomicity.

  76. Speaker 2

    What does it mean?

  77. Speaker 1

    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.

  78. Speaker 2

    So this operation will not be halfway.

  79. Speaker 1

    But non-atomic is an operation that I can further divide into multiple operations.

  80. Speaker 2

    It can be a half way.

  81. Speaker 1

    In our case, count + + is a non-atomic type of operation because it is divided from the inside in these three parts that I will read, increment and then write it in my memory.

  82. Speaker 2

    So it is possible that my one.

  83. Speaker 1

    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.

  84. Speaker 2

    Okay?

  85. Speaker 1

    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.

  86. Speaker 2

    Context can never be switched.

  87. Speaker 1

    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.

  88. Speaker 2

    It can't leave it halfway.

  89. Speaker 1

    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.

  90. Speaker 2

    Let's say one is account A and one is account B. So I call it ACC.

  91. Speaker 1

    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?

  92. Speaker 2

    I will deduct Rs.

  93. Speaker 1

    500 from this balance and increment Rs. 500 from this balance.

  94. Speaker 2

    So, Rs. 500 will come from here to here.

  95. Speaker 1

    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.

  96. Speaker 2

    It might have gone into a blocking state.

  97. Speaker 1

    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.

  98. Speaker 2

    So, this will become untrustworthy.

  99. Speaker 1

    So, in that case, what we do is, we do such operations, always try to make it atomic.

  100. Speaker 2

    Now you will say, how can we make it atomic?

  101. Speaker 1

    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.

  102. Speaker 2

    Synchronized.

  103. Speaker 1

    We will see this later. And one is atomic block.

  104. Speaker 2

    Integers.

  105. Speaker 1

    Now again, this is a proper class in Java, AtomicInteger. Apart from this, there is also AtomicDouble. We will see everything, what it actually means. We will also see how to work from inside. First, let's do one thing. Let's understand which operations can be atomic and which can not be.

  106. Speaker 2

    So that there is no confusion in the mind. Okay.

  107. Speaker 1

    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.

  108. Speaker 2

    Store x again.

  109. Speaker 1

    Apart from this, the most interesting type of non-atomic is called check then act.

  110. Speaker 2

    Check the net. What does it mean?

  111. Speaker 1

    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.

  112. Speaker 2

    Balance is greater than or equal to amount.

  113. Speaker 1

    So what will happen is, in the first condition, T1 enters this block and checks whether my balance is greater than or equal to amount.

  114. Speaker 2

    So initially, my balance is 1000 rupees.

  115. Speaker 1

    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?

  116. Speaker 2

    Let's say 600 rupees. It will say that the balance amount is more than that. There is no problem.

  117. Speaker 1

    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.

  118. Speaker 2

    400. But I have to deduct Rs. 500.

  119. Speaker 1

    But it has already entered here. My above validation has failed. Now if it has executed this statement.

  120. Speaker 2

    Balance minus.

  121. Speaker 1

    Amount, then my balance will be negative 100 and my transaction will be.

  122. Speaker 2

    Successful, but it should not be successful.

  123. Speaker 1

    Because you see, by combining both T1 and T2 transactions, I am giving 1100 rupees, but actually I have only 1000 rupees in my account, right?

  124. Speaker 2

    So this should not be possible.

  125. Speaker 1

    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.

  126. Speaker 2

    Okay, we will talk.

  127. Speaker 1

    About solutions later, now we are just looking at the problems.

  128. Speaker 2

    Now, what is the problem of visibility?

  129. Speaker 1

    You understood the race condition, you understood what is the problem of atomicity, and you understood what is the critical section and what is the shared resource.

  130. Speaker 2

    Now look, If.

  131. Speaker 1

    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.

  132. Speaker 2

    Those are intermediate results.

  133. Speaker 1

    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.

  134. Speaker 2

    Now what does it mean to read?

  135. Speaker 1

    It will pick it up from RAM and bring it in its cache memory or register memory. Now let's assume it's in cache memory. So it has stored this operation in its cache. That flag equal to true. Right?

  136. Speaker 2

    And it will perform an operation on it. Same T2 did.

  137. Speaker 1

    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.

  138. Speaker 2

    T1 dot start. T1 dot start. And T2 dot start. T2 dot start.

  139. Speaker 1

    Right.

  140. Speaker 2

    I'll do this. Now look, their logic is linked.

  141. Speaker 1

    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.

  142. Speaker 2

    Something like this. Now my flag is getting an error.

  143. Speaker 1

    Local variable flag defined in closing scope must be final and effectively final. Yes, we have seen about this in our nested class. What is this lambda? It is an implementation of a method. Anonymous class's further improvement.

  144. Speaker 2

    Okay. So I will do one thing. I will remove this line from here.

  145. Speaker 1

    Okay.

  146. Speaker 2

    So either I can put it in a new class or at the root level. Something like this. Okay.

  147. Speaker 1

    Now I will get another error, cannot make a static reference to the non-static field. So basically I will have to make it static.

  148. Speaker 2

    Why?

  149. Speaker 1

    Because my main method is also static. So you know all these rules, object oriented principles. If you want, you can make a new object, a new class, like we made in the case of counter. So you make a class named flag, in which you put a variable named f, a boolean.

  150. Speaker 2

    Variable, and you make it false.

  151. Speaker 1

    You can do anything, for now I have done it like this. So suppose in my demo 2, there is a static variable flag which is false. Thread 1 sleeps for a second and then it makes this flag true. And thread 2 keeps printing until flag gets true.

  152. Speaker 2

    And I have started both.

  153. Speaker 1

    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.

  154. Speaker 2

    So I don't know if there is a problem with visibility.

  155. Speaker 1

    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.

  156. Speaker 2

    Will be printed But what will happen if I run this code Thread to running, thread to running was printed and it stopped.

  157. Speaker 1

    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.

  158. Speaker 2

    Valuable.

  159. Speaker 1

    Right?

  160. Speaker 2

    So our output is the same as our first thought principle.

  161. Speaker 1

    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?

  162. Speaker 2

    So, this is also an infinite loop. I just removed printing statement.

  163. Speaker 1

    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.

  164. Speaker 2

    So here too it will be true.

  165. Speaker 1

    Basically in our RAM variable.

  166. Speaker 2

    But when this loop of T2 is going on, it is not reading from this RAM.

  167. Speaker 1

    When this while flag is reading again and again, it is reading from its cache which is getting false every time.

  168. Speaker 2

    So this loop is never ending.

  169. Speaker 1

    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.

  170. Speaker 2

    Volatile.

  171. Speaker 1

    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.

  172. Speaker 2

    Volatile int.

  173. Speaker 1

    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.

  174. Speaker 2

    And what used to happen?

  175. Speaker 1

    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.

  176. Speaker 2

    Okay? So, sequence in which instructions are executed. What does it mean?

  177. Speaker 1

    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.

  178. Speaker 2

    So CPU can also be reordered.

  179. Speaker 1

    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.

  180. Speaker 2

    It will reorder.

  181. Speaker 1

    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.

  182. Speaker 2

    Okay?

  183. Speaker 1

    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.

  184. Speaker 2

    0 Why 0?

  185. Speaker 1

    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.

  186. Speaker 2

    Answer is yes.

  187. Speaker 1

    So do system.out.println x. It will see x is 0. It will print 0 on the screen. So this is the reordering problem. It should have been 10i on the screen if it wasn't reordered. But if it was reordered and this line was executed earlier.

  188. Speaker 2

    Then only this will be true.

  189. Speaker 1

    If there is contact switching, then it will print 0 on the screen. But there are a lot of ifs and buts in this. If there is reordering and if there is contact switching after executing this line, It is possible that nothing like this happens and your 10 output comes.

  190. Speaker 2

    This is also possible.

  191. Speaker 1

    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.

  192. Speaker 2

    It is non-deterministic. But there can be a scenario in which a bug is introduced. Like this scenario.

  193. Speaker 1

    This is a bug scenario. When you do it in production, it may come once in 10. But it will come.

  194. Speaker 2

    It will come at some point.

  195. Speaker 1

    So whenever it comes, think how difficult debugging will be. Because you.

  196. Speaker 2

    It will take a lot of time to recreate that scenario.

  197. Speaker 1

    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.

  198. Speaker 2

    Synchronized.

  199. Speaker 1

    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.

  200. Speaker 2

    Right? Or what happens? Ordering issue happens.

  201. Speaker 1

    So, all these problems that we were reading, why was it happening? Because of interference between two threads.

  202. Speaker 2

    Right?

  203. Speaker 1

    So, basically, I can write the reason for thread interference. That it's possible that it's happening because of non-atomic operations. Because of shared resources. or because of race condition, or because of ordering.

  204. Speaker 2

    Visibility, etc.

  205. Speaker 1

    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.

  206. Speaker 2

    Okay, so I hope you enjoyed it.

  207. Speaker 1

    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.

  208. Speaker 2

    That's all for this video. Till then, thank you so much.