Podcast Lookup

Advanced Java Concurrency Explained | CompletableFuture, Fork-Join Pool, ThreadLocal & Virtual Threads

The Java Developers Hub

  • December 3, 2026
  • 1 h 22 min
  • Episode 10
Episode page
About this episodeModern Java applications often need to perform multiple tasks concurrently while maintaining performance, responsiveness, and efficient…
Modern Java applications often need to perform multiple tasks concurrently while maintaining performance, responsiveness, and efficient resource utilisation. Java provides powerful concurrency tools that help developers manage asynchronous operations, thread execution, and shared data.In this episode, we explore four important Java concurrency concepts: CompletableFuture, Fork-Join Pool, ThreadLocal, and Virtual Threads.You'll learn how to execute asynchronous tasks, coordinate multiple operations, divide complex workloads into smaller tasks, maintain thread-specific data, and use modern virtual threads to build scalable applications.Whether you're an experienced Java developer or advancing your knowledge of concurrent programming, this tutorial will help you understand the tools used to build high-performance Java applications.What You'll Learn
  • Understanding advanced concurrency in Java.

  • What CompletableFuture is and how it supports asynchronous programming.

  • Executing asynchronous tasks using supplyAsync() and runAsync().

  • Combining and coordinating asynchronous operations.

  • Handling exceptions in CompletableFuture.

  • Understanding the Fork-Join Pool framework.

  • How the work-stealing algorithm operates.

  • Breaking complex tasks into smaller parallel operations.

  • Understanding ThreadLocal and thread-specific variables.

  • Managing thread-local data safely.

  • What Java Virtual Threads are.

  • Differences between platform threads and virtual threads.

  • Creating and managing virtual threads.

  • When to use each concurrency feature.

  • Best practices for scalable and efficient Java applications.

Who Should Watch?
  • Intermediate and advanced Java developers.

  • Backend engineers building scalable applications.

  • Software engineers interested in asynchronous programming.

  • Developers learning modern Java concurrency.

  • Computer science students studying parallel processing.

Transcript

From the publisher

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

Advanced Java Concurrency Explained | CompletableFuture, Fork-Join Pool, ThreadLocal & Virtual Threads

00:00—
  1. Speaker 1

    Yes, so let's start. Welcome back Coder Army to our Java series. And today is the last day of this series. And today we are going to read about Fork Join Pool, Completable Future and Virtual Threads. These are all very interesting topics and you will understand them very easily. So let's quickly start our last lecture and end this series. So, if you haven't seen the last lecture, then you will have to watch it to understand this lecture. Because in the last lecture, we had explained about the future. We had seen that the future is a class in Java, which stores the result of an asynchronous request. So, basically, we write something like, let's say we have an executor.

  2. Speaker 2

    Executor.

  3. Speaker 1

    And we call a method on it, Submit. And here we can give a lambda expression. And we said that the lambda expression we give here is of type callable. And callable is nothing. It is just like runnable. It is just a return type of callable. Runnable does not have a return type. It is a consumer type lambda expression. It is a return type of callable. So we give a callable here. And we collect its result in a future.

  4. Speaker 2

    Right? Future let's say F1.

  5. Speaker 1

    Right?

  6. Speaker 2

    Why do we call it future?

  7. Speaker 1

    Because obviously if we execute it and submit it, we know what happens from the back. From the back, it will be executed inside the thread pool. So we will have a thread pool, a queue etc. So I don't know when my task will perform. Maybe it will sit in the queue. And our worker threads will also not be free to execute this task. So it can take some time. I don't know how much time it will take in future. So I couldn't store it in a normal variable. So Java gave us a special data type, future. Okay. Now the interesting thing is that this method of future, submit, it has multiple overloaded methods. One is callable, about which we had talked. It has more methods. If I tell you the total, then we have three overloads of future. Okay. And let's see which ones are there. One is the basic one, submit. which takes our callable. We had talked about this. Let's say I write here, we have the object of the executor, executor.submit and here we will give a lambda expression.

  8. Speaker 2

    Let's say no input and return 10. So I am returning something.

  9. Speaker 1

    And if I return 10, it is an integer type, so in the future of integer, i, something like this. And I know that in the future, if I do i.get, then I will get this value, this 10. But i.get, how does it work? We know that it blocks the current thread. Because it is possible that the value is not i. So basically, it blocks the current thread until i.get returns 10. And after that, our current thread execution starts. This was its first method, submitWithCallable. We also have a second type of this. which has submit with runnable yes we can also pass a runnable in submit so we know how runnable works we can write let's say executor.submit and if we pass runnable instead of callable then we don't have to give any output let's say no input and I want to print something so I write system.out.println hello Something like this So I just printed hello So this will be runnable And I can also receive this in the future But you might think.

  10. Speaker 2

    That we are not returning anything here So what will I receive?

  11. Speaker 1

    I will tell you what I will receive First of all, because future takes generics Now I am not returning anything So I will have to put a question mark here You know what wildcards are in generics And let's say I receive it in F1 Now obviously if I get F1. get anywhere Then I will get null Because I am not returning anything from here. But still why am I consuming it in F1? See, if I want, I should not utilize it here. I should just leave it as it is. But the benefit of this is that we will see that in our future class, there are some methods.

  12. Speaker 2

    Like f1 dot.

  13. Speaker 1

    isDone, isDone, this tells us whether our task is done or not, or cancel, through which we can cancel our task, right, so these methods, so that we can use them, that's why we receive them in a future variable, okay, so this is submitWithRunnable, and our last type is, which is submit, with runnable but with an actual message basically with a result with a predefined result Okay, what does this mean? This means that if we pass a runnable, it doesn't return anything. But if we want some output return, so that when we get f1. get, we understand that our task is complete, for that, Java has given us a submitWithRunnable with a predefined result, that you tell yourself what the result should be. And we write it like this, let's say, let's say executor.submit Here we will first pass our lambda expression, let's say I say no input and this is my lambda expression in which I am printing something, let's say hello something like this and once I have passed my lambda expression, I will take one more parameter comma and here I will give a message, let's say success Something like this.

  14. Speaker 2

    So, executor.submit takes two parameters.

  15. Speaker 1

    One is lambda expression and the other is success. Now, the advantage of this is that when we receive it in a future object. So, now I will receive it in future of string because my final output is string.

  16. Speaker 2

    Let's say f1. So, now if I get f1.

  17. Speaker 1

    Get then I will get the output success.

  18. Speaker 2

    And when will I get it?

  19. Speaker 1

    As soon as my F1 task will be completed, till then get will block our main thread So that I can see some output on the screen, I can keep a predefined result here with my executor.submit So these were the three overloads that we had to talk about to understand the future Apart from this, there are many interesting methods in the future That's why we are collecting runnable in the future Let's see which are those methods Now you know what get does. Get blocks the current thread. Let's say we have a future of integer type. f1.

  20. Speaker 2

    So if you perform.

  21. Speaker 1

    Get on this f1, then you know what will happen, whatever current thread is running, let's say main thread, it will block it, that wait, let it get its output, whatever the future output is, and as soon as the output comes, it will return it to the screen, and after that your main thread will start again, or whatever the current thread was, it will start again. Now, there is a problem with this, that what people do is, they directly use this after this, so you must have written some code, future f1 equal to, let's say, executor. submit and here you must have given a lambda expression. Let's say I am giving a simple lambda expression, no input and return 10, something like this. Now you know the meaning of this line is that I am saying that I have submitted it, that is, I have given it to an executor, right? He will have that thread pool inside him and he will have a queue and he will have a lot of worker threads, okay? In this hope, I have given that this task will be fulfilled by me. But suppose it takes some time to fulfill this task, okay? Till then, my task T1 is in my queue. It's possible that all my workers are busy, and my queue is empty, so I have put it in queue. Now, the more time it takes, the more time I have written in the next line, like f1.

  22. Speaker 2

    Get, the more time.

  23. Speaker 1

    My main thread will be blocked. So, if my main thread is blocked, then what is the benefit of it? Better than this, I would have done a synchronous operation. I did an asynchronous operation in this line and in the next line, I made it synchronous. Synchronous means, I said, stop everything else, until I get the result, I won't let anyone move forward. So it didn't work. So basically, you didn't let the main thread move forward, you stopped it until it got the result. So this is very similar to an asynchronous operation. Better than this, you don't execute it in the thread, you simply write it like this, integer F1 equal to, here you don't submit any task, you directly call a function, function which returns 10. We don't give any input, it simply returns 10. This is a synchronous function which we have been making till now. It wasn't necessary that you give it a thread, it runs asynchronously, and still you wait for it to complete its work and then I will move forward. I hope you understood why we write the whole threading code. We write the threading code so that we can make our code asynchronous. Concurrently we can execute things. Now my main motive was to keep this task running in the background, till then my main thread should keep running. But here I have blocked my main thread in a different line. So this is a little dangerous approach. What can be the right approach? The right approach is that I call it directly here.

  24. Speaker 2

    I say future f1 equal to.

  25. Speaker 1

    Executor.submit, let that task happen and keep doing something in my main thread, whatever I had to do. And when my work is done, I will write f1. get. By then, my output will have arrived. So I won't have to wait for the main thread. And by then, my main thread work will also be done. So this is its better use case. Rather than we wrote this and in the next line we wrote f1. get. Now, we saw that our get method can give two types of exceptions. One is your interrupted exception.

  26. Speaker 2

    And second is execution exception. ExecutionException.

  27. Speaker 1

    So you have to handle these two exceptions. These are both checked exceptions. So you have to keep it in the try catch block. Or you can throw these exceptions with your method. Now apart from this, we have seen one method, get. We have another method, which is an overload of get. Which takes a timeout. It takes a time and a unit. Okay, what does this mean? We write f1. get, let's say 2, 2 seconds. 2 seconds, I'll have to give it in timeUnit. You know timeUnit is a class in Java. Something like this. Suppose I'm saying that I'll wait for 2 seconds. You know get stops the main thread. So this get will only stop the main thread for 2 seconds. Whatever f1 is, let's say it's of future type. And you've written here, let's say executor.submit. Submit, here will be. submit and here you must have given a lambda expression, let's say return 10, it must have been collected in F1. So it is saying that I will wait for 2 seconds, and if the output comes for 2 seconds, then it is fine, I will print 10 on the screen, but if the output does not come, So I will throw timeoutException.

  28. Speaker 2

    This is interesting, you have to remember. When will timeoutException come?

  29. Speaker 1

    If our get method came within 2 seconds or whatever time it recorded, it did not give the output within that time.

  30. Speaker 2

    Now let's see the interesting method about which I had talked. One is isDone.

  31. Speaker 1

    Again, you must be understanding that this is a Boolean. It gives true or false. It tells whether our current task has been completed or not. Now, this is an interesting method because it does not block our main thread. So if you write f1. isDone, it doesn't block the main thread. It gives you the true or false output of the f1 task.

  32. Speaker 2

    Obviously, it doesn't give you the output.

  33. Speaker 1

    If f1. isDone is true, then you know that you have to You can get it and you will get your output. But again, if you do f1. done and then f1. get then it is better because you will know if your task is completed or not. If it is not completed then there is no point in doing f1. get, it will stop the thread. It is better to do f1. get when it is completed so that you get the output immediately. So this is an interesting method, it is very helpful to apply it. So that your main thread doesn't run asyncronously. Now we have another interesting method, cancel. cancel, now it takes an argument of type boolean and the name of this argument is may interrupt if running.

  34. Speaker 2

    If running, ok what does it mean?

  35. Speaker 1

    I will use it and tell you so let's say we have defined a future of type let's say integer i sorry f1 equal to let's say and here it will be written executor dot submit And here you would have given a lambda expression. Let's say no input and 10 output. Something like this. Now if I write f1.

  36. Speaker 2

    Cancel.

  37. Speaker 1

    And here I had to give a true fault. So let's say in the starting I give true. Something like this. So what does this mean? Let's understand this. This is very interesting.

  38. Speaker 2

    F1.

  39. Speaker 1

    Cancel, you want, obviously you can understand from the name, that whatever task we have submitted, I cancel that task. I don't want to perform that task. Now, because this task is asynchronous, you can have two choices. Choice 1, that the task hasn't started yet. You submitted, basically in the executor, basically as soon as you submitted the task, it sat in its queue, whatever its waiting queue is, blocking queue, because maybe no worker will be available. So, if it hasn't started yet, if not started, Then your task will get cancelled easily. There is no problem. The second case is that your task has started. So the task is already running. This is your second case, that your task has already started. Now here, further we have two cases, that depends on which Boolean expression you gave here. Here you gave, basically Boolean, may interrupt if running, that if your task is running, then can I interrupt it? You said yes, you can do it, true.

  40. Speaker 2

    So here too, two choices were made.

  41. Speaker 1

    If you had given true, then Java will try to interrupt your task So try to interrupt, we saw how the interrupt method works And you know, if your task is in a waiting or blocking state, then there can be an interrupted exception.

  42. Speaker 2

    So it will try to interrupt.

  43. Speaker 1

    But if you gave false, that you can't interrupt, then there is no other choice, you have to let that task finish. Now it can't be cancelled. So f1. cancel depends on the state of your task. If it doesn't start, it will be cancelled. If it has started, there are two choices. If you gave true, it will try to interrupt it. If it can interrupt, it will stop. And if it can't, it will throw an interrupted exception. But if you didn't interrupt, then it will remain finished. Now because you had cancelled, you have one more last interesting method, isCancelled. And you know, this is also a Boolean that will give you true and false and will tell you whether your task has been cancelled or not. So these were all the interesting methods that you can apply in the future. So let's say I write future in the class. You can apply these methods and this is very interesting. Now you must have understood why we try to collect our runnable in the future. Because we can also apply isDone, cancel, isCancelled on them. It's not necessary, we just need the output. Even if we don't get the output, the task can be canceled or checked whether the task is completed or not. Now, if we understand future and callable, then we will have to understand some limitations of future.

  44. Speaker 2

    What are the limitations of future?

  45. Speaker 1

    And these limitations invent a new thing in java which we call completable future. And this completable future is mostly used in our spring boot application or any production level application. More than future. We use future very less. We prefer to use completable future more. This is an advanced class of future. So first of all, let's understand the limitations. What do you think will be the limitation of our future?

  46. Speaker 2

    Limitations. Look.

  47. Speaker 1

    The biggest limitation of this is its get method. Whenever you do f1. get, I told you that we only block our main thread. And what is the problem because of this? And what is the problem because of this? This is the problem of our parallelism. We can't do asynchronous operation. Your main thread has stopped. So this is a big disadvantage of this. Its blocking nature. The blocking nature of f1.

  48. Speaker 2

    Get.

  49. Speaker 1

    So basically I can say that our future class is a passive class. It only allows you to check whether your task is done or you can wait till then.

  50. Speaker 2

    You can't do anything else.

  51. Speaker 1

    You can't do that if your result comes, then you did something else, connected multiple results etc. So this is its second disadvantage. It cannot connect or I can call it chain. multiple results. So because of this too, a big disadvantage arises. But our completable future removes these two disadvantages.

  52. Speaker 2

    We don't need to block in this.

  53. Speaker 1

    Although you can get call in completable future, but why will you do it? We have better methods in this that you don't need to block in this. You can do chaining here and you will see a lot of benefit of chaining especially We use chaining a lot in our production level code. We will discuss that as well. So, we have an advanced version of the future class. Let's understand how it works. So, completable future. First of all, when we were making our future, we used to write future of type let's say we made it of integer type name it f1 and where we used to call this f1 on any executor so we used to write executor dot submit And a lambda expression would pass here. Now this can be a callable or a runable. But what was this executor? You know it can be a thread pool executor. We might have made it somewhere up. Through our executors class. Executors is our utility class. We might have made a new fixed size executor. But our completable future, we don't need to explicitly make an executor in it.

  54. Speaker 2

    It uses its own executor from inside.

  55. Speaker 1

    So what we have to do is, to call this class, we make an object of completable future. completable future Let's say of type integer. So I can also call this f1. Let's call it f2. f1 is equal to Now, I don't need to run this in any executor. I have a static method in this class. I write, completableFuture.supplyAsync SupplyAsync, this method. And what does this SupplyAsync method do? Again, what our executor does, whatever task we are going to give here, basically, SupplyAsync will take a task.

  56. Speaker 2

    Task means, again, will give a lambda.

  57. Speaker 1

    You can give it a callable like no input, return 10. Like this. Give a lambda expression. And it will submit this task in an executor. We haven't made an executor yet. It uses a fork join pool executor from inside. Which we haven't explained yet, we will see that in this lecture. So it uses a fork join pool from inside. And you just give this task and it will automatically put that task in this fork join pool. And it will complete your task. How does this pool work? We will see that in a little while. But now think of a big idea. That there will be a pool from inside. A pool executor who will have threads. Who will have a waiting area, waiting queue, blocking queue as.

  58. Speaker 2

    We call it. So this is what our supply async does.

  59. Speaker 1

    Okay? Now, you must be understanding from the name of method that we will do something asynchronously, it will return us value, and we will collect it in our completable future in F2. Now, which method I can call on F2, we will discuss it after seeing its file. But no, here is an interesting thing. Here, we can apply two methods. One is this, supplyAsync. And the second one is runAsync. The difference is that we will do supplyAsync when there is a return value. For example, we are returning 10 and there is no return value.

  60. Speaker 2

    So basically, if we.

  61. Speaker 1

    Do runAsync, we will pass a runnable and if we do supplyAsync, we will pass a callable.

  62. Speaker 2

    Now, what did I say? That we should get some benefit from this.

  63. Speaker 1

    We called a separate method, made a separate class of supply async, completable future. Why didn't we directly execute it and submit it? We at least counted the losses of our future. That it is blocking, we can't do.

  64. Speaker 2

    Chaining in it.

  65. Speaker 1

    So, tell me the benefit of completable future. So, the benefit of completable future is, the most interesting, chaining.

  66. Speaker 2

    Chaining. What does it mean?

  67. Speaker 1

    Chaining means, you have to you can change the answer of this task for any other async operation.

  68. Speaker 2

    How?

  69. Speaker 1

    Here you have some core methods, we will see them in the code as well. One is thenApply, the other is thenAccept. Now you can understand by the name, thenApply It will transform, basically it will take a lambda expression of type transform. If you don't have idea of lambda expressions or types of functional interface, then you can watch that video, otherwise you can watch it later. For now, you can ignore this, we will code it and show you, then you will understand. And we will have the then accept method. It takes a consumer, then only your name is accept. It accepts, it will not give any output. And one is then run, these are the only three that we use. One is then apply, then accept, then run. Here it only works to run the task, no transformer, no consumer. Now we will see how it works and what is chaining actually. Now we will see in the code that what is chaining, then apply, then accept, then run and how we can perform a task from our completable future. So here we have made a demo.java file and we have to perform a task using completable future. So let's say first of all I make an object of completable future of type let's say integer and we name it let's say future and let's call it f1 equal to. Now I told you that we will not use any executor here. In this completable future class, there is a method called supplyAsync. And see what it expects from you, it expects a supplier. Now you know what a supplier is, it's a kind of function interface that returns an output. If you don't have an idea, it's okay, we'll just call it and see. But if you have a little idea, then remember we'll use supply async when an output comes and we'll use run async when an output doesn't come. So if I put run async here, then it takes off-type runnable object and supply async takes off-type supplier object. So we must be understanding its return type. Now let's do one thing, let's give a task here, let's say no output. and returns 10. Okay? Here I gave a simple lambda expression that I will not take any input and return 10 and put it in F1. Now obviously I did not make an executor of my own but completable future works on fork join pool executor from inside. Fork join pool executor. This task will perform in the background. Now I was telling you that I can also call f1.

  70. Speaker 2

    Get here.

  71. Speaker 1

    I can call this method. Obviously, it gives me some exceptions. So I have to put it in the try catch block. So I put it in the try catch block. I will do something like this and catch my exception. So let's do one thing, let's catch it from the exception class. Something like this. So I can do this, no problem. My output will also be 10 if I run it.

  72. Speaker 2

    So my 10 is here. But this is not a good use case.

  73. Speaker 1

    I made a completable feature because I didn't have to block my system. So what do we do? We don't use it like this. We use it by chaining it. So for example, here my output is 10. Now this is an asynchronous operation. I want when this asynchronous operation is over and we get 10 output, I multiply this 10 by 2.

  74. Speaker 2

    So I have a method here, then apply. So what can I do? First I write it in multiple line.

  75. Speaker 1

    I have written here, let's say, completable future.supplyAsync. And here I have written no input and get 10. And here I call another method, end.thenApply.

  76. Speaker 2

    Then apply.

  77. Speaker 1

    Now what do I have to do here? Now what do I have to do here? Let's go inside then apply. See, it expects a functional interface of a function type. Now you know what a functional interface of a function type is, right? So basically now we will give an input and transform it into an output. So now it takes the name of the function, so what is the input here? Input is what we are getting from here, completable, future, supply, async. And what we will get from this task is its input. So we will get an input of 10 from this task. So I will write whatever result I will get here. Let's say the name of the variable can be anything, result. I will multiply that result and return it with 2.

  78. Speaker 2

    Then apply. And this whole result will be stored in F1.

  79. Speaker 1

    So what I am doing here is completable future.supplyAsync and.

  80. Speaker 2

    thenApplyResult is result.

  81. Speaker 1

    Into 2 And you must be understanding by the name thenApply when it will work When this task will be performed then your thenApply will work So again to see its output I will have to print it somewhere So if I run it now then my answer is 20 which means my thenApply is working fine Now you can do this many times. You can write again dot then apply not then except then apply. Let's say you pass one more functional interface. So you pass here. This time whatever result comes, multiply it again by 3 this time. So first your 10, 10 into 2 will be 20 and 20 into 3 will be 60. Now if I run it, I will have to get it again. To check what is the output. Now if I run this, then I will get 60. And remember, then apply means first this asynchronous task will run in a thread, then this one will run when that work will be done, and then this task will run when the above two work will be done. Now apart from apply, let's say we do this as a comment, and here, sorry, we do this as a copy, and do this as a comment, and let's use this one more time. So that I can show you then accept. Now let's assume that instead of then apply, I call another method then accept. So what parameter does it take from me? Then accept takes from me a consumer type parameter, functional interface. So again, what does consumer parameter do? That it will not give you any output. So this is final, then accept. It will accept you. So what can we do? Let's say whatever result comes. Now, what does then accept mean? I just have to give an output. Now, what does then accept mean? I don't have to give any output. Now, what does then accept mean? I can't return any output. And the consumer will only consume. So, I can do something like this. Whatever result comes, I can take the input. Whatever result comes, do one thing. Print it on the screen.

  82. Speaker 2

    Result.

  83. Speaker 1

    Something like this. So, I can print it on the screen. I can't give any output. Now I am getting an error here and that is, type mismatch cannot convert from completable future void to completable future integer. Now obviously, what we have written here is, first supply async, input low and output 10. Now who is consuming this output? Then except says that whatever output will be 10, I will take it on my input and print it on the screen. That means the final output of this statement is nothing. Then accept finally consumes it. So F1 will not get integer type of completable future. It will get void type. So I have to put void here and my error will be removed. So again void is also a class in java. Void class proper. You can just return completable future of void. Where you know you will not get any output. Now you will understand the real benefit of our completable future.

  84. Speaker 2

    I had said. F1. get blocks it.

  85. Speaker 1

    And we were using it because we didn't increase the then except.

  86. Speaker 2

    So you must be wondering what is the benefit of completable future.

  87. Speaker 1

    Even now, no matter how many chaining we do, we have to get F1.

  88. Speaker 2

    Get.

  89. Speaker 1

    We have to stop our main thread. But now we don't have to do this. Because our then except is an asynchronous operation. It doesn't stop our main thread. Our main thread keeps running. And our output also comes with it.

  90. Speaker 2

    Now what should be its output? We will print 10 on the screen. So 10. Our output is here.

  91. Speaker 1

    Then apply returns a new value and then except consumes a value. It doesn't return anything, it consumes it. It is of consumer type and then apply is of function type. And finally, if I copy it and comment it, we get a third function which I call then run. And what does it take? If I go to then run, it takes a runnable type object again. It means that you just want to run something. So how can you run? Now runnable type means no input and you can perform any task here. Let's say I just print system.order.println, done. Something like this. So the runnable type interface's lambda expression doesn't take input.

  92. Speaker 2

    Simply we just printed done on the screen.

  93. Speaker 1

    Now if you use it and print it, then your screen will be printed as done. Done means the task is completed. So you have seen three methods, then apply, then accept, and then run. Now here is another interesting method, which we call then combine.

  94. Speaker 2

    And what does it do?

  95. Speaker 1

    It can give you the result of multiple completable future combined. How? See. I will comment this too for once. Now everything is commented. Let's make two completable features. I made one here. Let's uncomment it.

  96. Speaker 2

    I stored 10 in F1.

  97. Speaker 1

    Let's make one more like this. Let's name it f2. It returns, let's say, 20. So, one is f1, which returns 10. One is f2, which returns 20.

  98. Speaker 2

    Okay. Now, what can I do?

  99. Speaker 1

    Let's make another completable future. Of type integer, obviously.

  100. Speaker 2

    F3.

  101. Speaker 1

    Let's call it result. Equal to, let me write, f1 dot then combine then combine. Now, then combine means we have to combine the results of these two. So, it's first parameter will be, how do I combine f1 with f2? Here, I can give a lambda expression that how do I combine it? So, if I go inside then combine, then see, it's second parameter is by function. If you don't know all this, how many types of function interface can there be, then you can ignore it. But here, I just have to give a lambda expression that how do I combine f1 and f2?

  102. Speaker 2

    So, let's say, I give it like this. I have to combine them like this.

  103. Speaker 1

    I write, let's say, a comma b such that a plus b Something like this. So whatever the result of F1 and F2 is, write 10, 20 and add them. Means my output should be 30. Now you know what I can do to print on the screen. I can directly write here dot, dot, then accept, then accept. I want to write like this that whatever result I get here, I will print it on the screen.

  104. Speaker 2

    Result, something like this.

  105. Speaker 1

    Type will be misspatched and I will have to write void and now it should work Okay, we can't use result here because we have already used result. Let's say we use result 2.

  106. Speaker 2

    Simple. And here also result 2.

  107. Speaker 1

    Okay.

  108. Speaker 2

    So now it should work.

  109. Speaker 1

    If I print it, then my answer should be 30.

  110. Speaker 2

    Okay.

  111. Speaker 1

    Okay.

  112. Speaker 2

    I hope you understood.

  113. Speaker 1

    The most interesting part of this is that our chaining is non-blocking. It doesn't block your main thread other than get which is blocking. That's why there are many advantages of completable feature. And the supply async method we used, then accept, then combine, we use this a lot in our Spring Boot application. Okay, now let's move ahead and understand that I had told you that the completable future uses fork join pool from inside. Completable future. Which pool does it use from inside?

  114. Speaker 2

    Fork join pool. Fork join pool. But if you.

  115. Speaker 1

    Don't want to use this fork join pool, you want to pass an executor of your own, you can do that too. Because the method we call here, supplyAsync, has an overloaded method, which takes an executor from you too. So basically you can write, completable future dot supplyAsync. So whenever you call the supplyAsync method, you know, you have to give a lambda expression or a task here. So for now, I'll leave it empty. Or we can call it task, whatever you have given here. And here you can pass an executor of your own. So, it is possible that you have made an executor of your own above.

  116. Speaker 2

    Okay, how did you make it?

  117. Speaker 1

    It is possible that you have used the utility class of executors. Dot new fixed thread pool executor etc. And you have got an executor here and you can pass it here. If you want your completable future to use a specific executor. Right, don't use your own fork join pool executor. Use your executor, then you can pass on that here. Now we have talked a lot about fork join pool and we are using it here. But what is the meaning of this and how fork join pool works? Fork join pool executor, we will see about this and this is very interesting.

  118. Speaker 2

    So till.

  119. Speaker 1

    Now, the normal thread pool executor that we had read, what did we read about it? That we will have one thread pool in which there will be multiple worker threads. So here let's say there will be a worker1 is called t1, t2, t3, and t4. So let's say there are 4 worker threads. And there must be a queue. Now it must have a fixed size. Now you know that we have a task, let's say task1. We will see that we have a worker available. So let's say task1 is assigned to thread1. And thread1 equal to task1 went to do it. And thread1 disappeared from here.

  120. Speaker 2

    So we have 3 left. Similarly task2.

  121. Speaker 1

    Task 3, task 4, all these came and took T2, T3, T4 Now our thread pool is empty Now you know what will happen if task 5 comes? It will go to queue to wait Then task 6 here, 7 here, 8 here, 9 here And if task 10 comes, then you know what will happen? If we haven't achieved the maximum thread limit Then we will make a new thread So maximum thread pool size is here So you know how all this works.

  122. Speaker 2

    What is this Fork Join Pool?

  123. Speaker 1

    First of all, understand that Fork Join Pool brings more parallelism in our code. Let me explain the principle first. The principle is that if there is any task, which is a little big task, which I can break down into two sub tasks. I break this into sub-tasks. So how easy will my work be? One thread will do this sub-task and the other thread will do this sub-task and both of them will complete the task.

  124. Speaker 2

    Now think of this recursively.

  125. Speaker 1

    Divide these sub-tasks further into smaller sub-tasks.

  126. Speaker 2

    Like this.

  127. Speaker 1

    And divide this sub-task further into smaller sub-tasks. Same.

  128. Speaker 2

    Divide this sub-task further into smaller sub-tasks.

  129. Speaker 1

    This sub-task too. This sub-task too. And this sub-task too. And by doing this, This is our base condition. So basically, like our DSA is in recursion, right? So what I'm doing is, I'm recursively dividing my task into subtasks, right? Up to a base condition. Now all these small tasks will be executed independently and after that they will be joined again in our main task. So I divided a big problem into small problems, took out the solutions of those small problems and by combining these small solutions, made a big solution again. This is the approach of our fork join pool. In DSM, we call it divide and conquer approach. And fork join pool also follows this approach. It says, suppose you have a task, task 1, which comes here, comes in this pool to execute. So fork join pool says, why don't I divide this task into small tasks? And every thread can do a small part of it. Let's understand how all this happens. But I hope you got a basic idea of what fork join pool means. Now look, in fork join pool, fork means to divide. And the other one is join, right? To join this, we divide it and then join it.

  130. Speaker 2

    Okay?

  131. Speaker 1

    Okay. Now we will see how we break tasks into sub-tasks and how they are joined later. Now you have to assume that when I will explain to you how fork join pool works, you have to assume that we will have a task, task1, and this is a special task. It can divide itself into sub-tasks. We will see how it can be done in code. But assume it can do it for now. So how our fork join pool brings more parallelism that how its small sub-tasks can be executed individually. Okay.

  132. Speaker 2

    So, Let's understand our fork join pool below.

  133. Speaker 1

    This. So, in our fork join pool, some things are obviously common. This is our thread pool. We have a queue. We call it submission queue in the language of fork join. Submission queue.

  134. Speaker 2

    Okay.

  135. Speaker 1

    And let's say there are some threads here. So for now, to explain, I'm making two threads here, T1 and T2. Okay, suppose these are my two worker threads. Apart from this, in this fork join pool executor, there is one more thing. And that is, every thread has its own private queue. Yes, so this thread also has its own private queue. I'll tell you, that queue is a queue. And this thread also has its own private queue. And these queues have a special name. We call them work stealing queue. Work Stealing Queue. Okay.

  136. Speaker 2

    Stealing means the one who steals.

  137. Speaker 1

    Okay.

  138. Speaker 2

    Work Stealing Queue. Why do we call it Work Stealing? We will understand in a while.

  139. Speaker 1

    Okay. Now, what did I tell you? In Fork Join Pool Executor, we have a Thread Pool. There is a Submission Queue which is in Sub. We can also call it Blocking Queue. In this, we call it Submission Queue. And every thread has its own Queue which we call Work Stealing Queue. Okay. Now, by combining all of this, our Fork Join Pool Executor is made.

  140. Speaker 2

    This is our Fork. JoinPoolExecutor. Okay? Okay. Now see how it works. I said, we got a task1. Okay? Task1. If it was a normal ThreadPoolExecutor, then you know what we do?

  141. Speaker 1

    We see task1. Do we have any thread available? Of course we do. So, T1 will do this task1. So, I would have signed T1 will do task1. And T1 would have disappeared from here. Right? But it is not a normal executor. It is ForkJoinPoolExecutor. It means that it will divide this task into multiple sub-tasks. How will we do it?

  142. Speaker 2

    We will see later. Now we just have to assume that it will be divided.

  143. Speaker 1

    Now see, what will happen? As soon as task1 comes, thread1 will see that I can execute it because I am idle. So thread1 will divide this task into two subtasks. So here I make two subtasks. So subtask1 and subtask2. Something like this. And she will say that she will execute Subtask 1 and put Subtask 2 in her work-stealing queue. She will execute it after some time. So she made her own work easy. She said that she won't execute such a big task. She will execute Subtask 1 and put Subtask 2 in her personal work-stealing queue. So let's say here it has put st2, basically subtask2 and it went to execute subtask1. So let's say it went to execute st1. So I can write t1 is executing st1. Something like this. Okay. Now remember, this thread1 can further divide all these tasks as well. Let's say, st11, st12, something like this. Or it can further divide this as well. And how long does it do this? Until a base condition comes. So I just assumed, for the sake of simplicity, that the base condition came in the first layer itself. As soon as we divided it, these two are in the base conditions. We will see how to apply that base condition in the code. So, sub-task1 will execute our thread1 and sub-task2 will put it in its work stealing queue. In the hope that when I come back, I will execute it by itself. Interestingly, it is called work stealing queue because let's assume that we don't have any other task. And thread1 is busy working on st1. And thread2 is still idle. It doesn't have any task. So what will thread2 do? Because neither any task is available in this queue, nor is there any task in its own work-stealing queue, so it will steal this task from the other queue, i.e. thread1' s queue, and will say that I am working on it, I am free, they enjoy working on it. So basically, we can say that t2 went to execute st2, and I can remove st2 from here, it stole it from its work-stealing queue, so I will write here t2 went to execute st2, something like this. So, T1 is executing ST1 and T2 is executing ST2 When both of them will do their own work So, we will use the join method of fork join in the code You just understand that both of them did their own work and T1 and T2 came back here And whatever result came of ST1 and ST2 So, basically whatever result came of ST1 and ST2 We finally combined the result of ST1 and ST2 in the result of task 1.

  144. Speaker 2

    Something like this. So, this is our final result. Simple.

  145. Speaker 1

    So, you might not have understood it well. You will understand it better by looking at the code. How can we take advantage of the fork join pool? And obviously, we can't take advantage of every task at all. We can only take advantage of the task which you can divide into sub-tasks. The task which you can solve with divide and conquer approach. We will see which one it is. But you must have got a basic idea. Let's see another scenario. Let's assume, this time, let's remove this too. Let's assume we have two tasks this time. One is task 1. One is task 2. Something like this. And let's say a task 3 also came. Three tasks came together. One after one almost. Now this task 1 was a very small task. It could not be divided. So thread 1 could not divide it. So thread 1 thought I will execute it completely.

  146. Speaker 2

    So I can say. Let's remove this. So I can say. Let's say.

  147. Speaker 1

    Thread 1 went to execute task 1 completely. It might not be possible to divide it.

  148. Speaker 2

    Thread 1 is gone.

  149. Speaker 1

    Now task 2 could be divided but only once. So task 2 was divided into two subtasks. ST1 and ST2. Subtask 1 and Subtask 2. Thread 2 said that it will execute subtask 1 and Subtask 2 in its stealing queue. So here we have st2 and st1 executed So we can write st1 is executed by So we can write t2 is executing st1 Now see t1 and t2 are busy T2 is busy doing the first part of task 2 And now we have task 3 We will put task 3 in the waiting queue Why is it in the waiting queue and not in the submission queue?

  150. Speaker 2

    So that someone can execute it.

  151. Speaker 1

    Now task 1 is completed and T1 returns to the thread pool So I remove this arrow and task 1 is idle again and I remove this bond as well So now task 2 is executing ST1 and T1 is empty Now, T1 will check whether I have any work. Now, it can check two places. One is in submission queue because T3' s work is there. And the other is the work of ST2 in the other queue. Now, it will give priority.

  152. Speaker 2

    To submission queue.

  153. Speaker 1

    So, T1 will see that if there is any work in submission queue, then I will go to execute it. Not that it will steal its work first. First, it will do its work completely and then it will steal other's work if there is no work left. And whatever work is there in submission queue, it is the work of all of them. It is a shared resource, right? So now t1 will go to task 3 again. So I can assume that t1 went to task 3 again. Now assume that task 3 was undivided, it couldn't be further divided for simplicity. So it went to execute it. Now assume that t2 is still busy for the sake of simplicity. t1 came back after executing task 3. So t1 came back again. I will delete this bonding. Maybe ST1 is a big task and it is executing T2 So as soon as T1 came back, it saw that its work is also done here Submission is empty, no new thread is coming, no new task is coming Now I can steal its work So T1 will now execute ST2 And I will say that I can remove its work from here And as long as T2 will be busy, as soon as T1 and T2 will work, we will combine these two works and make our final result This is how the work of work stealing Q works. Remember the priority. First of all, the priority is given to submission Q. When his work is finished, then they will start stealing each other's work. Okay? Now, your main important question will be, how can we divide a task into multiple tasks and then join them? So, let me tell you, the tasks we were giving them, these were special tasks. They were not simply runnable or callable. They were not simply a normal class. They were not runnable or callable. They were special tasks of a type of object. So, Java has a class, recursive task. And there is another class, Recursive action So java says that if you want to make any task which can be divided, forked and joined later And our fork join pool executor can do this with it So you will have to make a task that either overrides this recursive task or overrides this recursive action. Basically, these are both classes, so inherit them. And they both have a method, overwrite it. When do we use recursive task? If you want to keep the return value of your task, And recursive action when you don't want to keep any return value.

  154. Speaker 2

    No return value.

  155. Speaker 1

    So recursive action doesn't return anything.

  156. Speaker 2

    Recursive task returns. We will see an example.

  157. Speaker 1

    Using a recursive task, you will clear everything in that example. So let me explain the example first. Suppose we have an array. Let's say 1, 2, 3, 4, 5. 7, 6, 9. Something like this. We have some elements. My task is that I want the sum of all the elements in this array. So 1 plus 2 plus 3 plus 4 plus 5. In this way, I want the sum of all of them. And whatever the answer is, give it to me in the output. Right?

  158. Speaker 2

    So this task is very simple.

  159. Speaker 1

    If I ask you to write its code, you will run a loop and add all of them and give it to me. Okay? But suppose the array is very big. It is a million or billion size array. Okay? So if you run a simple loop in it, then your order of end time complexity will be there. Right? I want to take advantage of multi-threading. Some work should be done by one thread, some work should be done by another thread. So, in my mind, I have simple simple fork join pool executor. Fork join pool. Cool. Because you think, this task is a divide and conquer task. I can say that, half of this number, I will give one thread to T1, and this half of this number, I will give one thread to T2. If both of them work parallelly, then my work will not be done in n by 2. After that, whatever will come, let's say S1, its sum is S2, I will just have to do S1 plus S2, right? The same T1 will think that I have so much work, I will give half of this to another thread and half of this I will do it myself, right? Same, half of this, half of this. You can keep dividing it like this, okay? With your base condition. Now base condition can be anything, let's say my base condition is that there is only one element, that is the base condition. Or it can be that there are only two elements, that is the base condition. You can make the base condition according to yourself. The base condition means that I will not divide further beyond that. Suppose while dividing, I have such an array left in which there is only one element, 1. Now I can't divide this, so I will say that the sum of this array will be 1. Or I may have a base condition that I have an array which has two elements. So the answer to this will be 1 plus 2 is equal to 3. I will not divide it further. I can easily remove the base condition and I can easily divide this work because this work is independent. Whether I add this one half first and then add this one and then sum both of them, then also it will be equal. Or if I keep adding this one after the other, then also it will be equal. So such a problem can be solved with divide and conquer. Recursion can be applied to it. Then we can give it in fork join pool. So let's write its code and see how we make it complete. So here I have taken my demo2. java file and you know what I am going to do here.

  160. Speaker 2

    We are going to use fork join fork join Pool Executor.

  161. Speaker 1

    Okay. So, first of all, what we had said, we have to make a class, let's say. Okay.

  162. Speaker 2

    I will name it sumTask. Okay.

  163. Speaker 1

    I have to make a task, which will perform sum. And I will have to extend it with recursive task. Recursive task. Something like this.

  164. Speaker 2

    Okay. And again, it uses generics.

  165. Speaker 1

    And I am going to make array integer. So, I will write integer here. I am going to use integer recursive task. Okay. Something like this. Now if I go to this recursive task class, then see this is an abstract class. So it will have an abstract method which I have to override. And the name of that abstract method is compute. So see this is compute. I have to override this. So I do one thing, I write at the rate override. And if you go and see how is the signature of our compute method in the recursive task. So see that protected abstract v type is compute. Now you know v is generic so it is of integer type. So I can write it here protected Integer type compute. Something like this. For now, I will write return 0 so that the error goes away. So here I made a class of sum task and extended it as recursive task. I can also write recursive action here. If my compute doesn't return anything. But I want to return something, so I took recursive task class. Now I have a problem statement that I have an array and I want to get its sum. So first let's make all that outside. So let's say I make a private Integer Array Arr Now suppose I get this array from the constructor I will keep two more variables One is private int start Okay Its starting location Which will be basically zero And a private int end Okay Which will be array.length Okay I need a start and ending index That's why I will be able to divide it Right So I took an Arr Start and end Now let's make its constructor So I take public sumTask SumTask It will give me two integer values, one integer array, one start and one end. And you know what we will do here? We will make this.arr equal to arr, this.start equal to start and this.end equal to end. Simple. Now let's move on to our compute method. We will see step by step. First of all, we will write a base condition like we write a recursive code. How we have to stop our code. After that, we will write our main logic here. What is the main logic? First we will divide the problem and finally we will join it. Divide means we will fork it and join means join. First we will fork it and then join. If you have solved any problem of divide and conquer in DSA then you can easily relate it. So first let's write our base condition.

  166. Speaker 2

    This is very simple.

  167. Speaker 1

    Now suppose you have an array which has two or less than two elements. So basically I can write if end minus start is less than or equal to 2. So, there are less than or equal to 2 elements. So, I don't need to further divide it. In that case, what will be my sum? In that case, I can easily calculate the sum. If I loop through it, then int i equal to, start from the start, i less than or equal to end, i plus plus, and every time I keep adding it in the sum, sum plus equal to arr of i. Something like this. Okay? And finally, return sum. This is my base case. If I have 2 or less elements, then I will add a loop. How much time will it take?

  168. Speaker 2

    Constant time?

  169. Speaker 1

    And if there is 1 element, then it won't take time. Sum plus equal to arr of i and return sum. This is my base condition. Remember, I could have solved this problem normally too. I would have added a simple loop and added all the elements. But I want to solve it parallelly using multithreading and I am using fork join pool in that as well. So I am complicating my code further. But we will understand the whole phenomenon in this way. So till now I have just made a class called sumTask, in which I have taken a array, taken start and end, made a constructor and I have to override the compute method. Here I have written my base condition. Now let's write our main logic. First of all, we will divide our array into two parts. So I will take out mid. And how can I take out mid? I can write start plus end by 2. This is a basic code for any array. If you have a starting and ending index, then you will understand.

  170. Speaker 2

    So I took out mid.

  171. Speaker 1

    As soon as I took out mid, I got one array from start to mid and another array from start to mid. This is one problem. And the other problem is from mid to end. One from start to mid and one from mid to end. So I have divided the entire array into two. Recursively, if I wrote this code, I would call my compute method. But compute doesn't take any parameter, right? My whole work is in the sum task class as a whole. So, what can I do here? First, I divided in mid. Then, I make two objects of my class. So, my class name was sum task. So, sum task became one. Left task. And similarly, sum task. I kept one as right task. I made two tasks. Left task, right task. And I made left task equal to new sum task. Here I don't have 3 things, so I gave array in array, in starting index I gave start and in ending index I gave mid.

  172. Speaker 2

    So I got this one.

  173. Speaker 1

    So as soon as I made this object, new sumTask array start mid, my constructor must have been called again. This time the array must have gone in the starting but in the end my mid must have gone. So I made my sumTask object with a small array, with this part array. Now same, you know what I can do on right task, I can do equal to new sum task And here I give array mid plus 1 and here I give end, something like this So this is my second.

  174. Speaker 2

    Array, right?

  175. Speaker 1

    Means I have made two objects of sum task, one left task and one right task Both take half half array, okay Now as soon as I did this, I just have to write one line on, I have to write let's say left task dot fork What did I do as soon as I forked? I said that I am putting this left task in my work stealing queue and I will do that work later.

  176. Speaker 2

    First, I want to perform the right task.

  177. Speaker 1

    So let's say this whole work would have come on thread 1 in our worker pool. So as soon as he saw this code and started executing it, he saw left task.fork. Meaning, I am saying that I have divided my main task into two parts, left and right. I put left in my work stealing queue. I will write rightTask.compute. I have called rightTask's compute method. As soon as you call compute, it will start doing right. As soon as it reaches here, it will recursively divide it again into two parts, left part and right part. It will put the left in its stealing queue and will go to compute the right. Then this method will be called, it can be from top to bottom, then it will be divided again.

  178. Speaker 2

    Which is just like recursion.

  179. Speaker 1

    And you know that once the base condition comes, where it will have to actually work. And till the time it has kept the work in its work stealing queue, it is possible that some other thread will come and do that work, that is, do the work of this left task. If you had written normal divide and conquer, then what would happen to you? You would have done the left task separately and the right task separately.

  180. Speaker 2

    Because you would have to do both.

  181. Speaker 1

    In any way, you can't get the sum of an entire area by doing half the work. If you work on the same thread, in a single threaded environment. So you have to complete the task. So even if you do it with divide and conquer, you know what you do? Left task dot compute, right task dot compute. So you write something like this. You write left task dot compute. Let's say its answer is int sum 1. And here you write int sum 2. Equal to writeTask.compute. Okay.

  182. Speaker 2

    Here will be int.

  183. Speaker 1

    And finally, you know what you would have done? You would have returned sum1 plus sum2.

  184. Speaker 2

    Something like this. Isn't it? This integer returns. So, you have returned sum1 plus sum2.

  185. Speaker 1

    Okay. Okay. Here. space should not come, something like this, right? You would have done this if you were working in the same thread.

  186. Speaker 2

    But I am saying why should I do both the work in the same thread?

  187. Speaker 1

    Now my work is, if I am working in multi-threading code, then one of the work of the thread is to work on.

  188. Speaker 2

    One of these.

  189. Speaker 1

    So let's say it will work on the right task, so right task.compute, but it will not work on the left task, right?

  190. Speaker 2

    So I don't need to work on the left.

  191. Speaker 1

    So I will just write something like this, that I am doing the left task as a fork. Basically, I am putting it in my work-stealing queue. But I am ready to work on the right task only. So, I wrote rightTask.compute. I will keep the answer in the sum2 itself. Now, I have done the right task. Now, think recursively. Let's think one step down. I am saying that as I have done rightTask.compute, I must have got the sum of all the right areas. Now, it is possible that the left task will work on some other thread. So, I will have to wait for that. So, I will do int sum1. I am waiting for my left task. So I will write here. join. Do you know what is the join method? Join method says that I will stop my current thread. Whichever is executing with my current thread. Till the time my left task thread is not executed. So when it is executed, I will put the result.

  192. Speaker 2

    Of it in sum1.

  193. Speaker 1

    It's possible that someone else didn't do it, it's possible that he had to do it. If no one stole his work, it can happen in a rare case, right? So he had to do it. But there is a very high chance that someone else must be doing this work.

  194. Speaker 2

    He just waited.

  195. Speaker 1

    That okay, left task will join, sum1' s answer will come and finally I will return it in sum1 plus sum2, right?

  196. Speaker 2

    So this is my join part.

  197. Speaker 1

    This. Right?

  198. Speaker 2

    Something like this.

  199. Speaker 1

    Okay?

  200. Speaker 2

    So, this is my complete code. I hope you understood it well.

  201. Speaker 1

    Okay? How I wrote the base condition, how I divided the main logic, and how I finally returned my join statement. Okay? Just remember, first solve it with simple divide and conquer if you have no idea about it. After that, you will understand this multi-threaded code better. But if you know simple, if you know DS well, then you would have understood it easily. Now, let's go to our main code and use it. So, look, first of all, I make an array int arr equal to Let's define it like this.

  202. Speaker 2

    Let's put 8 elements in it.

  203. Speaker 1

    Then we are going to make our own ForkJoinPoolExecutor. For that I have a class ForkJoinPool. Let's name it Pool. Equal to new fork join pool. Something like this. I have a class in my executor service. Which makes fork join pool. But it's better to use fork join pool's class in java. Now I have to make an object of small task.

  204. Speaker 2

    So let's say small task. T1. Equal to new small task.

  205. Speaker 1

    Small. Okay not small task sorry sum task is it. sumTask equal to new sumTask here I will pass my array starting index is 0 ending index is this length arr.length and what I will do is I have a method pool.invoke and here it takes a task so I have given it t1Task let's call it task and I have given this task here and whatever answer it gets stored in result int result And finally, I can print this result on the screen. And after that, I have to shut down this pool. So, this is the complete code. You know that I made an object of fog join pool, I made an object of small task, I gave this array in my main object, I gave starting and ending index, and called this pool to invoke. Now, the whole work will be done in the thread pool from the back. Do you know how it will be done from inside? I will have a result, I will print it on the screen, and I will shut down my pool. Now, let's run it. I am getting an array index out of bound exception. Okay, here we have given the ending index array.length. I will have to give array.length-1 because the last index will be less than the length. Its length is 8 but the last index will be 7. Okay, now let's run it. So, my code worked and my output is 36. So, sum of first 8 measures is 36 and my output is correct. I hope you understood the whole for join pool. We said that in our executors class, which is our utility class, there is a method in it. If you do new work stealing pool, New Work Stealing Pool, even then you will get a Fork Join Pool Executor from within. Still, it is recommended in Java docs that you always use the Fork Join Pool class rather than this. Now let's move on to our very interesting topic which is Thread Local. Thread local is a very simple concept. We know that the multiple threads we make share heap memory. Let's say I have a class called resource and I have a string in that resource.

  206. Speaker 2

    Let's say string name.

  207. Speaker 1

    So basically if this class executes multiple threads, t1, t2, t3, then all of them will share the name variable in this resource. But imagine a scenario where t1 wants to put something else in this name, t2 something else, t3 something else, but it can't because the heap's memory is shared. What will it do? It will raise condition, it can overwrite each other's names. So, Java brought ThreadLocal. ThreadLocal is a memory of every thread. ThreadLocal says that this name field will have its own value for everyone. So, for Thread1, its value can be Aditya. For thread 2, its value should be Rohit. For thread 3, its value should be Rohan. Something like this. Every thread can have its own value in it using thread local. You just don't have to make a string here. You have to make a thread local of type string. This is a special class.

  208. Speaker 2

    Okay.

  209. Speaker 1

    So, assume every thread will get its own private copy of this variable.

  210. Speaker 2

    Name will remain the same. But everyone will have its own value.

  211. Speaker 1

    Okay. How do we make it? It's very simple. Whatever your class is. Let's say your class was resource. You have created a threadLocal type object in it. threadLocal of type string. This also uses a generics. Let's again keep its name as name. Equal to new threadLocal Something like this. Now suppose you make multiple threads in your code, T1, T2, T3 and make them in the same way as we make thread T1 equal to new thread and you pass a runnable inside, same T2 thread, T3 thread, you are passing a runnable in all of them. Now how can you use this local variable name? You can use it by using the methods of thread local, we have special methods like one method is set One method is get, which you know will help you to set or get the name of this local variable. So you can write something like this. Let's say you have made a thread. T1 equal to new thread. And you know here you used to give a lambda expression.

  212. Speaker 2

    So here you give lambda, no input.

  213. Speaker 1

    But here you basically want to give a full functional of runnable.

  214. Speaker 2

    Something like this.

  215. Speaker 1

    And here you can write Let's say whatever your name is, name.set and whatever you want to set, you pass it here. Let's say Aditya, I passed it here. Something like this. Now, suppose you make a separate thread T2 and you write name.set Rohit. And finally, you know what you do? You start T1 and you start T2. Now suppose whenever the thread is running T1 and if there is a name.get in the code, then Aditya will always be there and whenever T2 runs and if there is a name.get in the code, then Rohit will always be there. So this is the simple concept of thread local that in a shared memory, everyone has their own private copy. This will never cause a raise condition and you don't need to put any locks because everyone has their own copy. So if I was printing system.out.println in this runnable And I would do name.get So I would get Aditya here And if I would do name.get in the runnable of T2 And I would get Rohit If I would do name.get somewhere and run thread T1, I would get Aditya And if I would do here, I would get Rohit This is the simple concept of thread local Now an interesting question arises, why don't we use local variables directly? We know that our stack space is not shared, it is private for everyone. But local variables are limited in our function. As soon as the scope of your function is over, your local variables are over. But your class, resource, is in heap. This means that this name is going to be filled for a long time. So this can be a good resource. So you may use it again and again. For that time, we use our thread local. Okay. If you understood this then we are moving towards our last topic which is very interesting and that is the topic of virtual thread. What is virtual thread in java? What was the story till now? We used to say that whenever we make our own thread like we write thread t1 equal to new thread and we pass a runnable here let's say Let's say we have passed a simple runnable here System.out.println Hello Something like this So, what we have done here is that we have made a simple thread Now whenever I said that we will do t1. start As soon as we write t1. start Our JVM tells our operating system to actually make a thread in the system So, let's say this is our JVM Here somewhere in the code we made our own thread.

  216. Speaker 2

    We made this JVM thread. JVM thread.

  217. Speaker 1

    So basically till the time we wrote this code, our thread only existed in JVM. Till the time we didn't write this line. But as soon as we wrote t1. start, we told our operating system. So let's say this is our operating system. Here we told it that you yourself made a thread in the system. And we linked our JVM thread to our operating system thread. So whatever I will do on this T1, it will actually be doing the thread of my operating system. Let's say I make another thread in JVM and start it too, let's say T2. start, then I will ask the operating system to make a thread at its end and link it to my JVM thread. Right?

  218. Speaker 2

    This is the concept till now. Simple.

  219. Speaker 1

    And this is the entire traditional way which we have been doing till now.

  220. Speaker 2

    But there is a big.

  221. Speaker 1

    Problem in this. What is the problem? The problem is that by doing this, you can't make a lot of threads. If you make a lot of threads, then a lot of threads will come in our operating system. And when CPU will execute them, then it will spend a lot of time in context switching. And we also know that the process of thread creation is a bit expensive. Every thread that is created, it takes space from 512 KB to almost 1 MB. So a lot of resources are consumed in making a thread, in managing it, etc. And here we have one to one mapping Every JVM thread is linked to an OS thread Every JVM thread is linked to an OS thread So whenever you make a thread It is actually making a thread in your operating system It is a real thread Now the problem here is Suppose you have made 4 threads Let me quickly make 4 threads 1, 2, 3, 4 So here real thread will also make 4 And all this will be linked in some way Now the problem is Suppose your first thread Let me make it like this Your this thread went to waiting state. Or it could have gone to blocking state. So let's assume it's waiting for an input-output device. Let's make it smaller. Let's say it also went to blocking state. So 2 threads out of 4 are in blocking state. So what will happen is, Your operating system can't use these two threads Because it might be waiting for input and output And you can't create more number of threads So there are two big problems Because JVM's thread is directly linked to our operating system's thread So if this is in waiting state or blocking state.

  222. Speaker 2

    Then this will also block So this will also go to.

  223. Speaker 1

    Blocking state Till then our operating system can't use these threads And we can't make more number of threads Because the more threads we make Our operating system will get a lot of load Right? But when do we need a lot of threads? If we are making our own website and we assume that whenever we get a client request, we will make a new thread to fulfill it. But this is a very strange idea. If you do this, you will make thousands of threads and your entire system will slow down. To solve the same problem, we came to the Executor Framework. So, what did Java say? Don't make so many threads. I will keep some number of threads in my pool and we will reuse them again and again. But the problem was that we didn't get much concurrency. Our concurrency remained limited. It could be 4 or 5 or 10 at a time. task can be executed, depending on how many worker threads are there. And our concurrency remained limited till there. But, there came the concept of virtual thread with java. A thread which is not physical, but virtual. What does it mean? Java said, let's work. The part that I manage, it manages JVM. You can make any number of threads in it. So you made one thread, another one. I will call all these virtual threads. Obviously, the normal thread you make is not a virtual thread. There is a proper syntax to make it.

  224. Speaker 2

    You call a method.

  225. Speaker 1

    But for now, suppose you made so many threads. How many did you make? 1, 2, 3, 4, 5, 6, 7, 8, 9. Yes, so you made 9 threads. But in the operating system, you can't make so many threads. Or you shouldn't make them. In OS, let's say, we have only 3-4 threads. Simple. Now here, you can make many more virtual threads. The concept of Java is that firstly, I will call all of them virtual threads.

  226. Speaker 2

    This is not real. This doesn't exist yet. Virtual thread. Virtual thread.

  227. Speaker 1

    Now, when you actually have to work on a virtual thread, let's say this T1 thread, when you actually have to work on it, then I will link a virtual thread to an operating system thread. So let's say T1 went to work, so I linked T1 to this thread, now actually the operating system will be able to work. Because virtual thread itself has nothing, it can't work. Thread is actually at the operating system level, which can execute from CPU. But CPU doesn't believe in any virtual thread, nor can it understand it. It can only deal with operating system thread. So you can make a lot of virtual threads But actually when you have to use a virtual thread As you are using it Then JVM will link it to an operating system thread You will say what is the benefit of this?

  228. Speaker 2

    Now see Now assume.

  229. Speaker 1

    This thread is being used This thread is being used This thread is being linked to this This thread to this And let's say this thread to this Right?

  230. Speaker 2

    So what did I say?

  231. Speaker 1

    8th Our 7th, 4th, and 1st. These 4 threads are being used. And the rest of the threads are being used. Now the advantage is that suppose this thread 1, T1, went to the blocking state.

  232. Speaker 2

    It went to the blocking state.

  233. Speaker 1

    It might be waiting for an input-output and went to the blocking state. But in that case, if it went to the blocking state, then Java will say, remove this dependency.

  234. Speaker 2

    Until our.

  235. Speaker 1

    As long as our current thread is blocked, why should I block the operating system thread? For that time, I will assign another thread which will be ready to run, which will be in our runnable state. So it is possible that it is in the to runnable state and is ready to run. And because it is waiting, so Java has assigned this 2 to this operating system thread so that it starts to run. Now, suppose for some reason it went to the to blocking state, then we will break this connection again. And we will connect all the alive threads with the ones that are ready to run.

  236. Speaker 2

    Let's say our 5.

  237. Speaker 1

    Something like this. So what I mean to say is that the threads that can actually run, we will link them to the operating system thread. And the thread that is in the blocking state, waiting for the input and output, waiting to acquire a lock, we will break this connection and give it to another thread so that it can actually run. which means we can bring more parallelism. Our operating system thread will never be idle. It will not be idle. It will be doing some work every time. It will be executing some virtual thread. So this is the concept of a complete virtual thread. Now suppose JVM 1 comes back from the blocking state again. So as soon as it comes back, we will see which of our operating system threads is empty. If it is not empty, then it will wait a little. If it is empty, then we will quickly assign it to our operating system thread.

  238. Speaker 2

    Now the good thing about this.

  239. Speaker 1

    Is that you can make hundreds of thousands of virtual threads.

  240. Speaker 2

    There is no problem.

  241. Speaker 1

    It takes minimum space.

  242. Speaker 2

    Our code will run efficiently.

  243. Speaker 1

    Because our operating system thread from inside will be limited. Or whatever operating system thread you will make, you will make it limited.

  244. Speaker 2

    What will JVM do?

  245. Speaker 1

    It will link your virtual thread with operating system thread. And this mapping will be one to many mapping. One operating system thread will be linked to many JVM threads. Remember this. So let's make a virtual thread in demo3. java and see how we can make it from java. So here's a simple approach. As we used to make our thread, we'll write We used to do it like this. And here we used to pass a lambda expression. So let's say the lambda expression is to print. Let's say system.out.println. So let's say I want to print the current thread's name. So thread.currentThread.getName. I can print getName. Okay.

  246. Speaker 2

    So here I have made my thread.

  247. Speaker 1

    Now this is my simple thread that I used to make. As soon as I do t1. start, my operating system thread will also be made and it will be linked one to one. But I don't want to make a simple thread, I want to make a virtual thread. So instead of making a new thread, I will call a static method in my thread class which is called startVirtualThread.

  248. Speaker 2

    Something like this.

  249. Speaker 1

    And if you go to start virtual thread, it also takes a runnable type object. So here I have given runnable. Now as I have written start virtual thread, so this virtual thread is also made. And because start is also written here, so if it gets an operating system thread, it will also be linked to it.

  250. Speaker 2

    I just have to call here t1. join.

  251. Speaker 1

    I have to wait for it to join so that my main method doesn't end. Before it executes, let's put it in try catch block.

  252. Speaker 2

    Yes.

  253. Speaker 1

    Catch exception Something like this.

  254. Speaker 2

    So now if I run this, my output will come. Let's run this. Empty output, okay. What have we done here? Okay.

  255. Speaker 1

    We have written currentThread.getName. We don't get name in our virtual thread. Okay.

  256. Speaker 2

    We just do currentThread. Thread.currentThread.

  257. Speaker 1

    Okay.

  258. Speaker 2

    If I print it, now my output should come.

  259. Speaker 1

    Absolutely. VirtualThread 20 slash runnable whatever the name is.

  260. Speaker 2

    Fork join pool 1 worker 1.

  261. Speaker 1

    Okay. So from inside it must be using fork join pool for some reason. Okay. So from here we have made our virtual thread. Here I can also print a message. Let's say says hi. So whatever the name of the thread was, that says hello. So if I print it, the answer will come, says hello. So here I have made my virtual thread. Now, why have I joined t1 here? If I remove it and simply let it execute like this and run it, then see what will happen. My output will not come Because this is a virtual thread So my main thread which was running Which was an operating system thread It did not wait for it to end That's why I put join here So that once T1 thread ends and I see its output Then I can close my main thread So it is behaving like D1 thread We had understood about it But this is not actually a D1 thread It is just a virtual thread So basically operating system or main thread does not wait for it Now this is the way to make a virtual thread, but we don't make it like this. We use a special method of executor. So we can write executor service, let's say executor, equal to, in our executor class, executors dot, there is a special executor, new virtual thread pool task executor.

  262. Speaker 2

    Executor. Virtual thread pool. Per task. Executor.

  263. Speaker 1

    Okay.

  264. Speaker 2

    So what it does. The thread pool it makes from inside.

  265. Speaker 1

    In that.

  266. Speaker 2

    It uses virtual threads. So it says. Virtual thread. Per task. Every task. Tries to do it in a virtual thread. Okay. So what I can do here. What I did earlier. I will run a loop. Let's say. Five tasks. Int equal to. I equal to one. I.

  267. Speaker 1

    Less than equal to 5 I plus plus and every time I will call executor.submit call ok here I have to give a runable so I will do one thing I will call no input and print print task executed by whatever the name of the thread is ok plus thread sorry thread dot thread dot current thread because I don't do. getname in my virtual thread and here my work is to shut down the executor so executor.shutdown something like this so I call it like this I made an executor new virtual thread pool task per task executor it will try to use virtual thread from inside and it will try to do these 5 tasks in virtual threads now see here I haven't given any number of threads so by default it will make whatever it makes so now if I run it So there is no output because I didn't wait for the main code. Let's do one thing. Let's make our main code sleep. So I'll write thread.sleep. Let's say for 3 seconds. And let's cache here. And let's cache here. And let's cache our exception e. Something like this.

  268. Speaker 2

    Now let's run it.

  269. Speaker 1

    So my output is 5, task executed by virtual thread 28, 25, 30, 22, 20. Whichever you have named from inside, my 5 tasks are executed and all of them went to different virtual threads. There won't be so many operating system threads made for me from inside. Operating system threads can be made, but very few. But no matter how many virtual threads can be made, there is no problem. Okay, I hope you understood virtual thread. Now as we discussed, where can we use it? Obviously, we can use it to make web apps. Where our every request can be a virtual thread. So basically, I can write API calls. Similarly, if you are calling database calls in DB, then because you know that sometimes you have to wait in multiple DB calls, right? So we can create virtual threads in it so that if one virtual thread is waiting, the other virtual thread is linked to the operating system thread. So in any such operations, we can use virtual thread. This is a very interesting thing, it was the latest in Java. So use it well, we have an executor made properly. That's all in this video, in fact, that's all in this whole series. I hope you enjoyed it, you must have learned a lot from this whole series. If you enjoyed it, then please do a hype, like the video, do a good comment. I really enjoyed teaching this series, I find Java very interesting. And I wanted to explain to you in the same interesting way.

  270. Speaker 2

    In depth.

  271. Speaker 1

    To clear all your doubts.

  272. Speaker 2

    Okay.

  273. Speaker 1

    If you also enjoyed studying with me. Then it's great. Give me a like.

  274. Speaker 2

    Comment. Okay. I'll meet you in some next series. Till then. Thank you so much.