Podcast Lookup

Executor Framework Deep Dive _ ThreadPool, Future & Callable _ Java Full Course #56

The Java Developers Hub

  • December 3, 2026
  • 1 h 19 min
  • Episode 16
Episode page
About this episodeManaging threads manually in Java can become complicated, especially when building applications that need to execute multiple tasks…
Managing threads manually in Java can become complicated, especially when building applications that need to execute multiple tasks concurrently. The Java Executor Framework provides a more structured and efficient approach to managing thread execution.In this episode, we take a deep dive into the Java Executor Framework, exploring thread pools, Future, and Callable. You'll learn how to submit tasks for asynchronous execution, retrieve results from background operations, and manage thread resources more effectively.Through practical examples, you'll understand how Java handles concurrent tasks and how to build applications that are more scalable, responsive, and efficient.Whether you're an intermediate Java developer or advancing toward professional backend engineering, this tutorial will strengthen your understanding of Java concurrency.What You'll Learn
  • Understanding the Java Executor Framework.

  • Why developers use executors instead of manually managing threads.

  • Understanding Executor and ExecutorService.

  • Creating and managing thread pools.

  • Understanding FixedThreadPool, CachedThreadPool, and SingleThreadExecutor.

  • How thread pools reuse worker threads.

  • Understanding Callable and how it differs from Runnable.

  • Returning values from background tasks.

  • Understanding Future and retrieving asynchronous results.

  • Using submit() and execute().

  • Handling task completion, cancellation, and exceptions.

  • Shutting down ExecutorService safely.

  • Understanding thread pool configuration.

  • Best practices for managing concurrent Java applications.

Who Should Watch?
  • Intermediate and advanced Java developers.

  • Backend engineers building concurrent applications.

  • Software engineering students studying multithreading.

  • Developers learning asynchronous programming.

  • Java developers preparing for technical interviews.

  • Anyone interested in building scalable, high-performance applications.

Transcript

From the publisher

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

Executor Framework Deep Dive _ ThreadPool, Future & Callable _ Java Full Course #56

00:00—
  1. Speaker 2

    Yes, so let's start.

  2. Speaker 1

    Welcome back Coder Army to our Java series and today we are going to read the most interesting part of our multi-threading topic about the Executor Framework. You will enjoy learning this because this is the thing that we use the most in multi-threading in production or in any project. So let's go to the screen and start it.

  3. Speaker 2

    Yes, so today we are going to read our.

  4. Speaker 1

    Executor Framework Now first of all I will tell you that there will be a lot of small topics in it but it is very simple. The content of the theory is a bit more in it but it is very simple. You will understand everything at once. Now for its notes, I will give you proper notion notes because there will not be enough iPad notes in it. There will be a lot of things in it, there will be small nuances, which will look better if you get proper written notes. So don't worry about the notes, it's a very interesting part, you will enjoy it. So let's quickly understand about the Executor Framework. Before that, we have to understand that what we were doing in multi-threading in Java, we used to make a lot of threads in multi-threading and we used to make it work. Otherwise, the threads we used to make, we used to do manual creation, right? But the manual creation of threads is a very tedious process and a very useless technique.

  5. Speaker 2

    For many reasons.

  6. Speaker 1

    If we list down the reasons, then let's say, first of all, we have memory allocation. See, whenever you create a thread, or you call the operating system to create a thread, right? So whenever you write t1 dot, so basically whenever you write a thread t1, T1 is equal to new thread and you know what you do? You pass a runnable lambda expression here and then you write t1.

  7. Speaker 2

    Start.

  8. Speaker 1

    So as soon as you wrote this statement, you gave a message to your operating system that you make a thread at the operating system level and in that And do that action which I have already done in runnable. Then your operating system will go and make a proper thread and will give it time to execute. Your thread will start executing. But in all this, a lot of resources are required. You know in Java, if you create a thread, then a thread gets a space of 512 KB to 1 MB by default. Right, its own stack space, its own program counter etc. Now if you create 1000 threads, then your storage is almost lost from 500MB to 1GB. So you create a lot of space if you manually create a lot of threads. So apart from memory allocation, if we look at another point, That is Operating System Scheduling. When you make a lot of threads, let's say you have made thousands of threads. You make a new thread for every work. Because of that, there is a lot of context switching. Because you know that the number of cores in your CPU is limited. Let's say you have 4 cores. And you have made thousands of threads in that. So almost every core will be sending 200-300 threads. Only then it will be able to perform the work. Now if it handles so many threads in one core, then it will have to do context switching again and again.

  9. Speaker 2

    So it will spend most of its time in context switching.

  10. Speaker 1

    And it will spend very little time in the proper work that it should do. And this process is called threshing in Java. Threshing means that our core is spending a lot of time in threshing. Basically it is being used in context switching. It is not able to spend time in our actual work. Third reason is thread creation time. Whenever you ask your OS to create a thread, it takes some time. Obviously, because system calls are involved. You ask your OS to create a thread and the OS will utilize resources for it. will create a stack space for it, will create a program counter space for it, and heap is shared. So a lot of time is utilized to create a thread. And even after doing all this, we are not able to use the thread very well. Whenever we create a thread by ourselves, Why can't we do it? What do we do with thread? We do it one time use.

  11. Speaker 2

    One time use.

  12. Speaker 1

    Like till now we were doing it in our code. We used to create a thread.

  13. Speaker 2

    We made a T1 thread.

  14. Speaker 1

    We gave it a task and we left it. Then we made a T2 thread for a new task. We gave it a task and we left it. If we keep on creating one thread to perform one task, then the problems above will be highlighted. The number of threads will increase in our program. Thread creation time will increase and memory allocation will increase. So what we did till now was a bad approach. We were making all the threads manually and we used to tell how to work with it. So this is a bad approach. Now this is bad because take a real life example. You have a restaurant. So what you do is whenever someone wants to eat something, you hire a chef. You make him cook a dish and as soon as that dish is made, you fire the chef.

  15. Speaker 2

    So every time you.

  16. Speaker 1

    Have to make a new dish, you have to hire a new chef.

  17. Speaker 2

    So this is what we were doing.

  18. Speaker 1

    Whenever we had to perform a task, we would create a new thread. As soon as the task was completed, we would leave that thread. Then basically the thread would terminate. Then a new task came, we created a new thread, performed that task and terminated it. So because of this, our thread creation time will increase again and again. If it is not terminated, then there are more problems. Then it will also utilize more memory of our system. And most of our CPU time will be spent on context switching. So Java saw that all this is a big problem. So Java introduced the Executor Framework. Executor Framework, okay?

  19. Speaker 2

    Okay.

  20. Speaker 1

    Now, you don't have to worry about the notes that we are writing here. Again, as I told you earlier, you will get all the notes in proper notion format. Now you just have to pay attention to the whole theory, because there is a lot of theory, but it is also very interesting. Now let's first see what the Executor Framework is. So Java said, what you used to do with threads till now, You used to tell me two things, right? First thing, what work you have to perform, whatever your task is, right? And second thing, how you have to perform it. Actually, you used to create the thread yourself, right? How to do, let's say, I'll write it down, okay? So, what comes in how to do? You used to create the thread yourself, right? And you used to pass the runnable object in it. So, you used to tell everything to Java by yourself.

  21. Speaker 2

    Right? Java said, you don't handle all this.

  22. Speaker 1

    Because whenever you give a responsibility to a programmer, it's possible that he doesn't fulfill that responsibility properly. Right? He makes multiple threads, the code gets slow, memory allocation gets too much, the context switching in the program gets.

  23. Speaker 2

    Too much, etc. etc. So, thread said, So, Java said, I'll give you a framework.

  24. Speaker 1

    Just like we have Java's collection framework, we also have an executor framework. Which says, just tell me which task you want to perform. So, the executor framework just demands one thing from you. Just tell me the task. Which one has to perform asynchronously. Now you know that the tasks performed in threads are done asynchronously. Asynchronous means that we give the task to the thread and we forget it. Because as soon as the thread gets the task, it will wait for its CPU time. As soon as it gets the CPU time, it will run the task and then it will be terminated. So basically it is an asynchronous operation. So the executive framework says that you just tell me a task that I have to perform. I will make a thread for that myself if I have to make it. Otherwise, I will reuse the.

  25. Speaker 2

    Thread that I have already made.

  26. Speaker 1

    Now we will see how to reuse those threads. But a big executor framework just says that the thread creation you used to do manually, right? Whether you implement runnable in it or extend your thread class, although we were always implementing runnable. But most of the time, whatever you do, he said, stop doing manual work, I will handle the executor framework, your work will be done, just give me a task.

  27. Speaker 2

    Now, how did it do this?

  28. Speaker 1

    There will be a proper hierarchy of the Executor Framework, like the hierarchy of our Collection Framework. But before we read that, we have to first see how did our Executor Framework promise to handle everything? It introduced a very interesting thing which is called Thread Pool.

  29. Speaker 2

    Now, what is a thread pool? How does it work? We will have to understand all that first.

  30. Speaker 1

    So, first of all, let's understand a thread pool properly. Let's take an overview of it. Let's take an idea of how it works so that we can understand the executor framework better.

  31. Speaker 2

    Okay. Now, look. Thread pool. This is very interesting. Imagine that you have a pool.

  32. Speaker 1

    Okay.

  33. Speaker 2

    And in that pool, there are a lot of threads already made. Let's say, T1. T2, T3, T4, and T5. Let's make 5 threads, T5.

  34. Speaker 1

    There is a pool in which 5 threads are already made. And we call these threads as worker threads. Why do we call them as workers? Because they perform some work, so we call them as workers. Now, Java's thread pool says that I already have a big pool of threads. You don't need to create a thread by yourself. I have already made it here. I call them workers. You just give me a task. Let's say you gave me a task, task 1. What will I do with that task? I will assign a thread to that task. And that thread will go to perform that task. That means it will disappear from my thread pool.

  35. Speaker 2

    Now there will be 4 tasks left in my thread pool. 4 threads, sorry.

  36. Speaker 1

    Then you give me a second task, you gave me task 2, again this task came, I will assign it to another thread and it will perform the task. Now there are only three threads in my thread pool. By doing this, you keep giving me tasks, because I already have threads, I will ask them to work and they will bring your work. Now here is a very interesting thing that when thread T1 performs your work, then it will not terminate, but it will come back into the thread pool by doing its work.

  37. Speaker 2

    Start. Sorry. Start.

  38. Speaker 1

    Thread pool says that I will manage the life cycle of all my threads by myself.

  39. Speaker 2

    I will not let them terminate.

  40. Speaker 1

    As soon as you perform any work, with this, I will bring the worker back here as soon as it is idle. So that we can reuse our threads. So the most interesting concept of thread pool is that it reuses threads. What is the benefit of this? Obviously, we don't make a lot of threads with this. In our system, context switching is less. So everything is controlled. You don't need to do anything by yourself. So this is a big idea of thread pool. Let's understand a little more about this. In java, there is only one Q in the thread pool. Let me make it here. There is only one Q in the thread pool.

  41. Speaker 2

    Now what is Q? Imagine that we have 5 workers here and 1 is our queue.

  42. Speaker 1

    Which has 4 spaces Imagine that you are giving many tasks to complete this thread pool So you gave it task 1 You said, here is my task, perform it. So, as soon as you gave it task 1, first of all, it will see, is thread available in thread pool?

  43. Speaker 2

    Answer is yes, available. So, what will it do?

  44. Speaker 1

    It will do a mapping here, that okay, task 1 is will perform T1 thread and T1 thread will go away from our thread pool. Something like this. Now our thread pool will be left with 4 threads. After that, let's say you immediately gave a new task, task 2.

  45. Speaker 2

    Task 2.

  46. Speaker 1

    Task 1 is not over yet. Task 1 is doing T1 thread. It may take time to do it. It is an asynchronous work. As much as T1 thread will take time, it will take all of it. Till then, we have only 4 threads left in the worker pool. Now you gave task 2. It did a mapping again that task 2 will perform T2 So again T2 also went from the thread pool and so on Now you must have understood You can give more tasks here Let's say you gave task 3, you gave task 4, you gave task 5 Something like this And all these tasks will also keep threading T3, T4, T5 So T3, T4, T5 and so on I will make it a little smaller Something like this So here we can write task 3 is performing Here task 4 And here task 5. Now because of this, our entire pool is empty. Now let's assume that as long as you have given 5 threads, like task 5 was assigned to task 5, task 1 was finished. So as soon as task 1 was finished, T1 was free. So as soon as T1 was free, it will return to our pool. So we will write that T1 worker thread returned to the pool. And this task is finished. So let's say I say, let's cut this, this task is performed. Now, let's assume our task 2 is also finished. So again, what will happen? T2 will also come back into our system, into our pool. And I will say this task is also finished. Now, what will it do after coming back? It will wait for a new task to come. So let's say, if now I here, let's say, If I give a task 6 and task 7 here, then they will also handle T1 and T2.

  47. Speaker 2

    How?

  48. Speaker 1

    I will assign task 6 to T1 and T2 to task 7 and they will start working again. Now let's see the work of Q. Let's assume our worker is empty. All the threads are working. Now let's assume a new task comes. We have task 8. Now we will check if we have any worker to perform this task. The answer is no. All the workers are busy. Do we have space in the queue? The answer is yes. So we will insert this task8 in the queue. And you know what is the queue? First in first out. We have put the task8 here. Now as soon as any worker is empty, the worker will check this queue. Is there any task in the queue with which I can work?

  49. Speaker 2

    Right? So let's say, after our work, T3 comes back here. T3. Okay? And T3 sees that there is task 8 in the queue. So what will T3 do?

  50. Speaker 1

    It will start performing this task 8. It will start implementing it. Right? Now assume that T3 is still empty. Basically T3 is not here. Our worker is empty.

  51. Speaker 2

    Pool is empty. And more tasks are coming. Let's say task 9 came. Task 10 came.

  52. Speaker 1

    So what will happen? They will keep on inserting in the queue. Let's say task 9, task 10, task 11 and so on. Once our worker is also empty, our pool is also full, now a new task comes, task 12. So first of all, we will check in our worker pool, we will say that we have one thread, there is no answer, there is no thread, we will ask that there is space in our queue, there is no answer, there is no space in the queue, now what is happening? Now there can be two things with this task 12 Either our executor pool creates a new worker thread So as soon as he creates a new worker thread He will ask the worker thread Which is the first task from our queue, task 8 He will go to perform it There will be one space in our queue And we will insert task 12 First thing If he doesn't do this Then the second option we have is We will do task 12 Ignore. We can't perform this task because we have filled the entire space. We don't have any worker available and we don't have space in the queue. So we have to wait until a worker comes back to perform a task. I hope you got an idea of how our threadpool works. I gave you a simple example of a threadpool. There are multiple types of threadpools. We have a fixed threadpool, a cache threadpool, a fork join pool, and their work is slightly different. But look, Most of the work will be that everyone will have a pool of threads. Everyone will have a queue. Even if no one has a queue, we will discuss it later. But most of the work will be that our tasks will come. If the workers are available, then they will perform the task. If the workers are not available, then we will put them in a queue. And if our queue will be full and the workers are not available, then either an executor will make a new thread.

  53. Speaker 2

    Every executor has its own rule.

  54. Speaker 1

    If he can't make a new thread or can't make a new worker, then we can discard that thread. Now here too, there are many different policies, but this is the big thing about our whole thread pool. Java said that I will handle all this by myself, you don't have to do anything, you just have to give this task, this task is your work, Java does all this work on its own. Now interestingly, the task that we talked about, what is this task?

  55. Speaker 2

    It is nothing. It is our runnable type object.

  56. Speaker 1

    Right? We remember that in thread, we used to pass a runnable lambda expression. It is the same. All these are runnables. We give them a runnable, that take this runnable and perform it.

  57. Speaker 2

    That is the task.

  58. Speaker 1

    Right? And what will Java do? It will assign a runnable to this thread.

  59. Speaker 2

    Okay? So if I tell you roughly, what happened? We gave a task. What is a task till now? It is nothing. It is a runnable.

  60. Speaker 1

    And that task went to our Executor Framework Now who implements this Executor Framework? A Thread Pool. Executor Framework has a Thread Pool. We will discuss.

  61. Speaker 2

    About this now.

  62. Speaker 1

    And what does Thread Pool do? Thread Pool has a lot of workers And one of those workers gets assigned a task and our work starts performing. So basically I say that the task starts executing. This is the entire flow that is performed from our executive framework. It uses a thread pool from inside. Multiple types of thread pools can exist, we will see that later. But the work of a thread pool is to assign a task to a worker. Now let's see a small code how we can make our own executor and perform some tasks with it. There will be some codes that you won't understand because we haven't studied all the methods yet. So I have taken a file called demo.java and here I have to perform a task using executor.

  63. Speaker 2

    Framework, using the executor framework.

  64. Speaker 1

    So now I will write some code, maybe you have to understand something in it, because we haven't used it yet, basically we haven't understood about it, no problem. But you see what we are doing now, let's make an object of an executor service, let's say executor. Now see here I have made an object of an executor service, basically its reference variable. And I don't need a thread pool from inside. So I won't do a new executor service here. What is an executor service actually? It's an interface. I need its implementation. So I have a utility class in Java. Whose name is executors.

  65. Speaker 2

    Executors. And in that I have a new class.

  66. Speaker 1

    FixedThreadPoolExecutor And here I can give number of threads Let's say 2 Okay So let me tell you What I have done here Later we will understand this well I said Make an executor service Reference variable Executor Which is I use executors in a utility class And it gives me a FixedThreadPoolExecutor In which I have 2 worker threads Right So what we had made in the diagram That we had a thread pool So, let's say we have created a thread pool, which has two worker threads. And the reference variable of the thread pool we have created is the executor. Now, we will give the task, the runnable object, to this executor. And the executor will perform our task using this thread pool from inside.

  67. Speaker 2

    Okay.

  68. Speaker 1

    So, we have made two threads. That means, we have only two workers. So, let me do one thing. I will make the number of tasks as 5. We give 5 tasks. So, for that, I can run a loop. Let's say int. i equal to 1, i less than 5, i plus plus.

  69. Speaker 2

    Okay?

  70. Speaker 1

    And what do we do every time? We call a method of this executor.

  71. Speaker 2

    Executor. And the name of the method is very simple. Execute. Executor dot execute.

  72. Speaker 1

    If I go inside this method, then it will take a runnable type object from me.

  73. Speaker 2

    Okay? A command. Okay?

  74. Speaker 1

    So I have to give it a task. Now you know, whenever I have to give a runnable, I pass lambda there. So let's say I will pass. Don't take any input. And what do I have to give in output? Let's say I have to print on screen. Let's say task i isPerformedBy and I want to see which thread is performing it so to see that you know what I can write inside I can write thread dot current thread so that I get current thread dot get name get name something like this let's do it in multiple lines so that it looks easier. Something like this. Now I am getting some errors in i. Local variable i is required to be final and effective. Now because we have taken a lambda and we are using i in lambda. So you know we saw in nested classes that if you use a local variable like this then you have to.

  75. Speaker 2

    Make it final effectively. There is a simple way for that.

  76. Speaker 1

    I make a variable taskId and assign it to i. So, taskId is equal to i. And I pass taskId here. So, I make a local variable and pass it here. So that our i is effectively final. So, we had studied all this in nested class. If you don't know, then you can watch that video. So I made 5 tasks from 1 to less than or equal to 5. And in each task, I performed an action. I told this executor, whoever is our executor, who has a thread pool inside.

  77. Speaker 2

    Which thread pool? A fixed thread pool. Which thread pool is this? We'll see later.

  78. Speaker 1

    It has 2 worker threads. So I told him to do this. I'm giving you 5 tasks back to back. So as we had written task 1 and task 2 in our diagram, so I gave him 5 tasks back to back. And I told him to perform this action in each task.

  79. Speaker 2

    And what is this action?

  80. Speaker 1

    I'm just printing task This task is performed by and whatever the thread name is.

  81. Speaker 2

    So what will happen in the background?

  82. Speaker 1

    When I used to make my own thread, I used to write something like thread t1 equal to new thread. And here I used to pass a lambda of runable.

  83. Speaker 2

    So I could pass something here. Let's say print hello. For example. Yes. So print it here, let's say hello. Something like this.

  84. Speaker 1

    And I used to tell this t1 that t1.

  85. Speaker 2

    Start. So as I used to do t1.

  86. Speaker 1

    Start, our operating system used to create a thread and whenever it got time, it used to come in running state and perform this task. I am saying that I am not doing all this manually. I just made a task. This is my task. I made 5 tasks like this. And I told my executor.

  87. Speaker 2

    So, as I declared 2 threads here.

  88. Speaker 1

    From inside, our executor must have made 2 threads for us. Operating system must have made 2 threads for us. Right? And those 2 threads will be used to perform these 5 tasks. Now, task is 5. But there are two threads. What does this mean? Two threads will be busy performing two tasks. The remaining three tasks will go to the waiting queue.

  89. Speaker 2

    The queue that we made. How long will they wait in that?

  90. Speaker 1

    Until any of our worker threads come back to execute them. Right? This means when I print them on the screen, So I should get the information of only two threads Like I have written thread.current thread.getname So I should get the names of only two threads But we have five tasks So five tasks will perform two threads So before that I have to write an important code After doing everything I have to shut down my executor And this is very important You should always do this Otherwise your executor will always be on And these threads will always remain in memory So let me show you the output So look, first our task 2 is performed by pool 1 thread 2, then task 1, pool 1 thread 1. So two tasks 2 and 1, thread 2 and thread 1 have utilized the pool. After that our task 3, 4 and 5 were left.

  91. Speaker 2

    When did 3 work?

  92. Speaker 1

    When thread 2 got empty. And then 4 got thread 1. Now these two are working with it, our two worker threads are busy. Then 2 got empty and we gave it task 5. So look, here thread 2 is there, but they performed our five tasks. I hope you understood what happened there. We made 5 tasks there, so let's say task 1, task 2, we made it till task 5. Behind the scene we had an executor who had only two threads, worker thread T1, T2 and we might have a queue. So what will happen is that task1 will take thread1, task2 will take thread2, and task3, task4, task5 will have to wait in the queue. As soon as a worker thread is free, it will take out a task from the queue and will start implementing it. This means that the worker was always 2 and the task was 5. Now, interestingly, this entire thread pool framework becomes the backbone of your web development. If you read web development in Spring Boot, our entire executor framework becomes the backbone of it. Because think about it, we get multiple requests from the client on our server. Now, what does that server do? It follows that request. It executes that request. So, if multiple clients, let's say C1, C2, C3, will send a lot of requests at once, So here we have an executor who has a lot of worker threads and every worker thread's work is to handle a client's request. Now here we can't make unlimited threads, we can't do that as soon as a client comes, we will create a new thread and make it work.

  93. Speaker 2

    A new client came, created a new thread and made it work.

  94. Speaker 1

    Because if thousands of clients come at once, then we will create thousands of threads, right? You think what will happen to our system? That's why threadpool says that I will keep a limited number of threads and I can perform the same amount of work at once. If I get more work than that, then I will put them in my queue and tell them to wait a little. Basically, I will reduce my concurrency a little, I will make my things a little serialized. Now let's see the hierarchy of our entire executor framework. So this is the hierarchy of our Executor Framework At the top comes an interface called Executor And it is extended by another interface called ExecutorService The object we made in the code was ExecutorService ExecutorService is implemented by three classes One is ThreadPoolExecutor, one is ForkJoinPool and one is ScheduledThreadPoolExecutor Before ScheduledThreadPoolExecutor, there is another interface called ScheduledExecutorService So this is a small hierarchy of our entire Executor Framework. You just have to remember that at the very top is the Executor Framework. And within this, all our thread pools are made. Executor doesn't make thread pools directly, it's a new class. Executor Interface doesn't have a thread pool directly, it doesn't implement a thread pool directly. First of all, we have another system, another interface, Executor Service, whose object we made.

  95. Speaker 2

    Why does it come?

  96. Speaker 1

    Because it includes many such methods which are useful to manage our thread pool. It has only one method which we will see now, which is called Execute.

  97. Speaker 2

    There is only one method, Execute. This is just a functional interface.

  98. Speaker 1

    Rest, the most interesting method is with Executor Service, which manages the entire thread pool. And as I said, we can have multiple thread pools. So one is threadpool executor, which is a normal threadpool. Another one is fork join pool, which is a different type of threadpool. In this, the rules change a little. Another one is scheduled threadpool executor. What does it do? It can schedule the task to execute in the future. Again, we will see a little bit about this. So we have multiple threadpools. They follow different rules. Like we just made a cooper. In that, the rules will change a little bit. There is an executor service that manages all of them. And above all of them, there is an executor interface that has only one method, execute. And this is our hierarchy. Our job is to study this hierarchy and use the executor framework. So let's start with our executor interface. So let's say we have an interface called executor in Java. And this is a very simple interface. It has only one method, which is void execute. There is no return type, it is the name of the execute method and it takes a runnable type object, let's say R. Something like this. So it is saying that you give me a runnable type object, I will execute it. Now what will I use from inside, which thread pool will I use, that is my work. But I will execute it, your work is to give me a task. Now, our executor can use any thread pool from inside. It can use a simple thread pool. The one we saw above, basically this one. It can use a fork join pool. It can use a schedule thread pool, etc. But you just call its execute method. Your task should be performed. So, this is very simple. There is nothing in it. It is just an execute method. You just know that it is a declare because the interface is not defined. After this, the second interface that comes is of executor service. Executor service. Now why did Java introduce this? Because it has all the methods that manage all the threadpools. Let's see which methods are there because they are more interesting. Now look, obviously there is execute in this too. This will come from our parents. Execute method is simple. Which you know takes a runnable type object and performs work with it. Like Like we saw in the code, we made an object of executor service and performed the task in it.

  99. Speaker 2

    The task was. execute.

  100. Speaker 1

    Now apart from execute, it has a very interesting method and we call that method submit.

  101. Speaker 2

    Submit. Now this method will look like execute.

  102. Speaker 1

    This also performs an asynchronous task. So basically if we have a thread pool, there will be multiple threads in it. Let's say thread 1, thread 2, thread 3, thread 4. You gave it a task. So what you can do is, assume this is the whole executor. Basically our thread pool plus our queue, whatever the queue is, we call it an executor.

  103. Speaker 2

    Like we make it. And what you do is execute.execute.

  104. Speaker 1

    As soon as you give a runnable type object, our executor will take this task and assign a thread to it and make it work. This was the work of the execute method. This is also the work of submit, but it is a little different from this. Let's understand what is different. First of all, this is our submit method, which I write, let's say, executor.submit, we call.

  105. Speaker 2

    It like this.

  106. Speaker 1

    The task that it takes is not a runnable type, it is a special type, which we call callable. We haven't talked about callable in java yet, but callable is very much the same as runnable, that is, callable is also a task. The only difference is that callable also returns something Runnable never returns anything. Rest callable is also an interface like runnable. To implement that, you can pass a lambda expression. It has a run method. It has a call method. The work is the same from inside. You will give lambda to implement run. And the work is the same when you write executor.

  107. Speaker 2

    execute.

  108. Speaker 1

    So our execute method takes a runnable object, here it will take a runnable task, basically you can give it a lambda and submit takes a callable object. So see, how did you give a runnable object here? If you want to give a lambda, then how did you give it? You would give something like this that I am not taking any input, let's say and print something on the screen, let's say system.out.println hello.

  109. Speaker 2

    Simple. You gave a task. So I used to say that this task is runnable.

  110. Speaker 1

    You said that there is no input and you just have to print something in the output.

  111. Speaker 2

    This is a consumer.

  112. Speaker 1

    You used to give a consumer type lambda expression here. Reason being, our runnable never returns anything. If you remember, we never made a runnable that returns an output. And callable is only that which returns an output. If I give a lambda expression here, let's say I said, don't take input and return let's say 10 plus 20.

  113. Speaker 2

    Simple. Suppose I have given this lambda expression.

  114. Speaker 1

    So, this means I am returning a value which is 30 and this object of mine is callable. So, there is only difference between runnable and callable that our runnable doesn't have return type, no return type. And callable has return type, return type.

  115. Speaker 2

    Okay.

  116. Speaker 1

    So basically I can write that the method we have, submit, so I write it like this to use it. Executor.submit I am submitting the task. I am not running it, I am submitting it. Submitting means I have to give a callable and it will have a return value. And let's say it is a very simple task, I will give a very simple lambda. Don't give any input and return 10. So this is also a kind of callable. Now what did I say? It will return something. Now what will it return? It is returning 10. But where do I store this 10? This is an integer. So can I do this? Let's say I store integer.

  117. Speaker 2

    In i.

  118. Speaker 1

    Can I do it? Absolutely not. Because look, what things do I store in integer i? If you think carefully. I write something like this in some code. Integer i equal to let's say 4. I can write something like this. This means I am saying, make a memory.

  119. Speaker 2

    Shut up.

  120. Speaker 1

    Now you think, what things do I store in integer i? I can write something like this in my code. As I had written till now, integer i, let's say, equal to 4. What does this mean? I say, utilize a memory whose name will be i and its value will be 4. Meaning, I have put this 4 directly in this memory. But I know, when I write executor.submit, So I don't know when this task will perform. Maybe it will perform immediately. Maybe it will perform after a few milliseconds.

  121. Speaker 2

    Right?

  122. Speaker 1

    Because submit means I gave it to the thread pool. Now the thread pool will handle when this task will perform. Maybe there is no thread available after that. So we have to wait for this task in the waiting queue.

  123. Speaker 2

    Right?

  124. Speaker 1

    Until a thread comes in the thread pool to execute it. So till the time it is waiting, will our integer i remain the same? The answer is no. So writing this code is wrong in Java. This is a synchronous code. Integer i expects a value instantly. But this value will be given to you asynchronously. It might be given after some time. So Java has made a special data type for this. Whose name is future in Java.

  125. Speaker 2

    Future.

  126. Speaker 1

    So from the name itself, we can understand that the value given in the future, will be given asynchronously. So we have taken it in the datatype called future. Now again, future also uses generics from inside. So we will write future of integer. We will get the future value of an integer. And let's say I can take it in a variable f1 and equal to, I will put it here. Let's say f1 equal to our executor.submit. So basically, it will return me a future type object. Future is a class in Java, a new data type, which expect the output asynchronously. So here we learned two things. First, we learned what future is. And we learned what callable is. So we should understand these two things. Now, if we understand a little more about future. So what did you say here? We did the task submit. Task submitted.

  127. Speaker 2

    Okay. So, as soon as you called execute.submit, you said I have done the task. Submit. Okay.

  128. Speaker 1

    Now, the task will be run in your background. Task run in background thread. background thread. Because we have given that task to our executor. So whatever thread pool will be in it, it will perform this task. We don't know when it will do it. It can be done immediately if the thread is available to it. And if the thread is not available now, then it can be done some time later. So I can say that our task will keep running in the background. Then whatever result will come, stored in Future. So whatever result we get, we store it in future type object. I have written here, whatever return it gives, store it in F1, which is of type future. And finally, if I want to see what result I got in F1, like here it must be 10.

  129. Speaker 2

    So I have a function, I can write, f1.

  130. Speaker 1

    Get.

  131. Speaker 2

    Okay, f1. get.

  132. Speaker 1

    So basically, by doing f1. get, I can see the output. Now, this get method is very interesting. As I told you, I don't know when its output will come. Maybe it will come after some time. But suppose you wrote f1. get in the first line. So, will you get the output immediately? Maybe the output is not ready yet.

  133. Speaker 2

    Absolutely. So, f1. get is a special method. What does it do? Our current thread.

  134. Speaker 1

    Current.

  135. Speaker 2

    In which f1.

  136. Speaker 1

    Get will be written, suppose you wrote it in the main thread So this block blocks the current thread and says to wait until the output comes in the future So as soon as the output comes, then our main thread will start working again And the output of f1 will also print on the screen So let's quickly do this in code So here I have made a demo2. java file And here I have to see about future and callable future and callable. So, we will make it very simple. Let's say, first of all, I will make an object of executor service. Right, like we made earlier. Again, we will name it as executor. Equal to, I want an executor. So, I will use my utility class executor. Dot, new fixed thread pool. And let's say, I will keep thread 2.

  137. Speaker 2

    Okay, like before.

  138. Speaker 1

    Again, we will see later which executors we have made and which thread pools we have made. But for now, let's do one thing. I want an object of future type of type integer.

  139. Speaker 2

    We haven't imported the future here. Future.

  140. Speaker 1

    Yes.

  141. Speaker 2

    Of type integer. Okay.

  142. Speaker 1

    I'll name it f1. And how will I get it? I'll get it if I submit it on this executor. And what will it.

  143. Speaker 2

    Take to submit?

  144. Speaker 1

    Okay. And if I go to submit, it takes a callable type object.

  145. Speaker 2

    And what is callable?

  146. Speaker 1

    I have an interface which has only one method, call. Again, this is also a functional interface like our runnable.

  147. Speaker 2

    Right? So I can pass a lambda expression here.

  148. Speaker 1

    So I'll give no input and return 10.

  149. Speaker 2

    Simple. Tend, something like this. And see, it will come in our future.

  150. Speaker 1

    Now whenever I write in my code, basically in my main code, f1.

  151. Speaker 2

    Get.

  152. Speaker 1

    So this means I am saying, block my main code for as long as my f1. get output doesn't come. And as soon as the output comes, after that I will restart my main thread. Now it is giving me an error, which is unhandled exception, interrupted exception.

  153. Speaker 2

    Means it will throw an exception. So for this I can put a try catch block. So I write try. Who to try? This one.

  154. Speaker 1

    And here we will catch our exception E Something like this Now if I run my code, I should get 10 output Let's run it once 10, absolutely So until I get 10 output, remember my main thread was blocked So if I had taken 3 seconds to perform this task Then my output would have come after 3 seconds If you don't believe me, then see I can do it here Let's say thread, let's do one thing, we will have to do try catch block again thread.sleep, so whatever thread performs this work, I am sleeping it for 3 seconds. And let's catch exception E. And as soon as this thread sleeps, I am returning 10. Something like this. You know that if my multi line is lambda, then I have to write a return statement.

  155. Speaker 2

    So I wrote this code. Now see, the output that will come here, f1.

  156. Speaker 1

    Get, will come after 3 seconds because my main thread will be blocked until I get the output in f1. And when will I get the output in f1? First we will wait for 3 seconds and then return 10. So until the output in f1 comes in the future, our main.

  157. Speaker 2

    Thread will wait. So let's run this. So our main.

  158. Speaker 1

    Thread is waiting and after some time our output will be 10 Now let's see what other methods are there in our executor service Till now we have seen execute Which takes a runnable type object, submit Which takes a callable type object, remember it will take runnable This will be callable, and you know the difference between them.

  159. Speaker 2

    There is no return type of runnable. There is a return type of callable. Okay. We have one method. Shutdown. Shutdown.

  160. Speaker 1

    And I told you that you always have to write this method. We didn't write this in our last code, which is very wrong. Whenever you use your executor, you write a shutdown method. So that you tell your executor to shut down. Now what does shutdown do internally? Shutdown says that I won't accept any new task. So let's say this is my thread pool. It has multiple threads and this is my queue. I will allow all the current threads to be executed and once they are done, I will close my thread pool and I will not accept any new task. So during this time, when I have written a shutdown, if I get a new task, I will reject it. I will allow the old tasks to be completed first and then I will.

  161. Speaker 2

    Close my entire thread pool.

  162. Speaker 1

    So, before terminating, it waits for the current tasks to be performed. For example, if two workers are busy, T1 and T2 workers are busy doing some work.

  163. Speaker 2

    So, let them complete the work first.

  164. Speaker 1

    As soon as they complete the work, I will terminate my thread pool. But during that process, I will not take any new thread or new task. Now, apart from this, there is another method. whose name is shut down now. Now you must be able to understand from the name. It says that I will not take any new task and I will terminate all my old tasks. But again, because Java cannot control the threads completely, so this is not a guarantee that your running tasks will be terminated. In a way, you are requesting and trying to terminate those tasks. So let's say T1 and T2 are working and you have called shut down now.

  165. Speaker 2

    So I can request T1, T2 to stop right now. Stop in the middle. Leave the work.

  166. Speaker 1

    But it is possible that they perform the whole work and come back.

  167. Speaker 2

    And then I shut them down.

  168. Speaker 1

    So sometimes shutdown now can also work like shutdown. And sometimes it can literally break all our tasks. Stop all the threads. These are the four main methods that we can use in our executor service. Executor submit, shutdown and shutdown now. Apart from this, there are two more methods. Which we will probably use sometime. One is invoke all. And one is invoke any.

  169. Speaker 2

    Okay. Now this is a little special method. What does invoke all do? Invoke all takes a list of callables from you. Takes a list of callables. Okay. Let's say you call them tasks. Okay. And invokes those tasks at once. Right. So basically what you were doing with submit. Right.

  170. Speaker 1

    If you want to submit many tasks, then you put a loop. So you write like this. Let's say for i equal to 1 to i less than equal to 5. i + + so basically you want to submit these 5 tasks so you write here executor.submit submit and here you give tasks one by one like this our invoke all says that you give me a full list of callable and I will execute it together ok so basically we say list of callable let's say tasks And you know what a callable is, it gives an output like a runnable. So you gave a list, let's say list.off And here you have passed a lot of callables, one returns 10, one returns 20, one returns 30.

  171. Speaker 2

    So you have passed a lot of list of callables. And after that you wrote on our executor, executor.invokeAll And you gave tasks. So it will invoke all the tasks And you know what it will return? It will return a.

  172. Speaker 1

    Future object But it is a list of callables So it will return a list of futures So you can collect it in a list of futures.

  173. Speaker 2

    Let's say futures Right?

  174. Speaker 1

    Something like this. And after those futures, if you get them one by one, you will get all the tasks. You can code this yourself. You make a task, make a list of it, off the list, put multiple tasks in it, and invoke all call on our executor, like we just made an executor, and give all those tasks.

  175. Speaker 2

    It will give you a list of futures.

  176. Speaker 1

    Loop through those futures, get the dot once, and you will get the output of all the tasks. Once you get 10, once you get 20, once you get 30, and so on. But again, the two main methods that we have, In our ExecutorService Right, we were talking about this since then, ExecutorService The two main methods that will be there in this Will.

  177. Speaker 2

    Be this, one will be your Execute.

  178. Speaker 1

    And one will be your Submit These two are special methods Okay, do you know why?

  179. Speaker 2

    This takes Runable.

  180. Speaker 1

    This takes Callable Now I told you one special thing about them That NoReturnType And this is called ReturnType But there is one more special thing about them. If there is an exception in runnable, then it gets lost. I can write basically, exceptions lost. But in callable, exceptions are not lost.

  181. Speaker 2

    Not lost. I can give you proof of this in code. Let's do it quickly. Yes. So, I have taken demo3.

  182. Speaker 1

    Java.

  183. Speaker 2

    So, what do I do quickly?

  184. Speaker 1

    I get an object of an executor service. Let's say executor. Executor. Equal to, let's say, our utility class, executors.new fixedThreadPool. And I'll take the size of threadPool as 2. I want it to be workerThread. Now I'll perform two tasks here. Let's say, I'll do executor.execute. Execute, here I have to give a runnable object So no input, and perform a work, let's say int x equal to 10 by 0 So see, here I am intentionally trying to get an arithmetic exception Okay, so divide by 0 should come And similarly, let's take an object of future Future of type integer Okay, and here I give it f1 equal to Executor. submit so I call it submit and here I give a callable let's say no input and do one thing return whatever I printed here because we can't return here I say return what should.

  185. Speaker 2

    I return 10 10.

  186. Speaker 1

    Divided by 0 something like this ok here future error is coming because it is not imported now it is imported ok you see everything comes from my concurrent package executor service executor future everything ok so let's say if I try to print f1. get So I'll do f1. get and again I'll have to put it in the try catch block And here I'll do catch exception e So here I wrote an execute and here I wrote a submit Now I'll do the submit code comment So here my exception should come first Okay, so what does exceptionLost mean? exceptionLost means that I can't catch this exception. Because my execute doesn't return anything. So I can't get this exception anywhere. So even if I write this inside a try block, let's say I made a try block here, and inside that, I did all this work of the executor, even then I will get an exception, I won't be able to catch this. Let's say I catch this here, exceptionE, okay? And I print here, let's say, catched executor catched Execute exception.

  187. Speaker 2

    Execute exception. Okay. So this won't be my print. Even now my exception will come. If you look at it carefully. So look. Again exception. Right.

  188. Speaker 1

    I can't catch this. Because this exception has come in a different thread. I am trying to catch it in the main thread.

  189. Speaker 2

    Okay. So I can't handle this exception. But again. If I look at my future case.

  190. Speaker 1

    In the future case, now look what I did in the future, execute.submit 10 by 0 means the exception should come here too But I have written f1. get inside the try catch block Now let's print something here too, let's say.

  191. Speaker 2

    I write.

  192. Speaker 1

    Cached SubmitException So I have cached the submitException, so let's see if I could catch it Absolutely catch submitException.

  193. Speaker 2

    I could do it. Right? So I can catch futureException.

  194. Speaker 1

    Right? But I can't catch my executeException because it's in a different thread. Now, to handle the exception of execute, there's a class called threadFactory.

  195. Speaker 2

    But again, we're not going there.

  196. Speaker 1

    Now you just have to understand that we can easily handle our submitException.

  197. Speaker 2

    Okay? I hope you understood this.

  198. Speaker 1

    Now, in our entire hierarchy, if we go back to our hierarchy, then here's our hierarchy. We have seen our Executor Interface and our Executor Service Now we have to see about different types of Thread Pools One is Thread Pool Executor, Fork Join Pool, Scheduled Thread Pool So first of all, let's see about our Simple Thread Pool Executor As we have discussed about it What is this? First of all, it is a Configurable Engine Which has a limited number of worker threads One Queue To hold extra request, Q to hold extra request. Here I am saying extra task.

  199. Speaker 2

    Okay. And there are some rules.

  200. Speaker 1

    Right. That how many threads, how many worker threads can we have. How big can be the queue. If our queue gets full and workers get finished. Then what we have to do. So basically there can be some rules. That means it is configurable as a whole.

  201. Speaker 2

    Okay.

  202. Speaker 1

    So the main diagram of this. You have to remember that this is our pool. This is our queue. And in this pool there can be worker threads. So let's say there are 4 worker threads.

  203. Speaker 2

    T1, T2, T3 and T4. And this is called a thread pool.

  204. Speaker 1

    Okay, till now when we used to make an executor, we used to write something like this, we used to write executor service, and we know that executor service is an interface itself, right? We used to make its object, reference variable, basically executor equal to. And here, we used to write new thread pool executor like this, we used to use our utility class, whose name was executors, executors dot, and here we used to take a made up executor, whose name was new fixed thread pool.

  205. Speaker 2

    FixedThreadPool.

  206. Speaker 1

    Right? And here we used to pass the number of worker threads, let's say 2. And our executor would be ready from inside.

  207. Speaker 2

    Okay?

  208. Speaker 1

    So you must have understood the benefits of this utility class first of all. Java said that you don't need to make all the executors by yourself. I have given you the made-up executors. executors class. This is our utility class. It has a fixed thread pool. Similarly, you will get many more types of thread pools in it. Cache thread pool, single thread pool, we will make that later.

  209. Speaker 2

    But I hope you got the idea that this made-to-make.

  210. Speaker 1

    Executor gives us. Now look, executor is a utility class, right? But the engine inside it, which is actually working, is called that thread pool, which is basically our fixed thread pool method, which makes a thread pool executor, right? The thread pool executor in our hierarchy, that makes our new fixed thread pool, right? This means whenever we write this, new fixed thread pool, then this method will do something like this from inside. New thread pool Executor. It would make an object of a thread pool executor. Something like this. And it would pass some values in its constructor. Now, we don't have to make it by itself. That's why Java makes it by itself. It makes a default.

  211. Speaker 2

    Okay.

  212. Speaker 1

    Why don't we have to make it by itself? Because making it is a little complicated. In this, we have to give a lot of things in the constructor. We have to configure a lot of things. So, Java says, why do you have to handle so many configurations? I have given you the configurations made by me. Yes, if you have to handle a lot of specific things, or if you have to change it, then go and make an object of this thread pool executor Now again, for the interview perspective, we have to understand how it works. And again, if you understand the internals, you will also enjoy it a lot. So let's see how our new fixed thread pool executor looks like from inside. So see, this thread pool executor, when you create it, you have to pass a value in the constructor. So it takes five values. Which values does it take? I will tell you once. So one is the integer current pool size. Current pool size Now we will see one by one what we say One takes integer max pool size So I can write it as maximum pool size One takes keepalive time in long Now this keepalive time so we have to take its unit too So one takes time unit Let's say unit And one takes blocking queue What kind of blocking queue does it need? Now off type runnable because it can hold runnable. Let's say the name is work queue. So this is how our thread pool constructor looks like. If you want to create it yourself, if you want to write new thread pool executor, then you have to configure these 5 things. First of all, our current pool size. See, there is no current pool size.

  213. Speaker 2

    It is saying how.

  214. Speaker 1

    Many minimum number of threads should be there, which should always be alive, right? So whatever your pool will be, there will be some minimum number of workers in it. Let's say, according to this, we said 2. So 1 and 2.

  215. Speaker 2

    T1, T2.

  216. Speaker 1

    So these are 2 workers which will always be alive. They will always be present here, right? To perform any task. This is current pool size, okay? After that comes your maximum pool size. Maximum pool size. Let's say we have set the current pool size as 2 before the maximum pool size. Now let's set the maximum pool size as 5. This means that how many maximum threads are allowed in our pool. Basically, the current pool size is 2 and the maximum is allowed as 5. This means that in our thread pool, Our workers can be from 2 to 5. And when will these 5 workers be made? I will explain the rules now. But one is the current pool size, how many minimum workers should there be? One is the maximum pool size, how many maximum workers can you create? So basically, the maximum number of workers you can create, the more concurrency you can create, right? That means you can perform that number of unique tasks together, right? After that, we also look at the keepalive time and time unit. After that, we come to the third number, work queue. Work queue. Now, what is this work queue? This is the same queue that we make in front of our thread pool, right? So, we say, what type of queue should it be? We can have two types of queues. One is of fixed size. One is of unlimited size. We can make two types of queues. So, you can choose a queue from this. Now, I will tell you what their name can be.

  217. Speaker 2

    Okay?

  218. Speaker 1

    So, these three will be clear to you. Current pool size, maximum pool size, and our work queue. Now, let's come to this keep a lifetime.

  219. Speaker 2

    So, look.

  220. Speaker 1

    We have a keep a lifetime. We made a maximum pool size of 5. Initially, there will be 2 threads and 2 workers. But sometimes, we can increase the number of workers. We can increase the maximum number of workers to 5. We can increase the maximum number of workers to 5. So we can configure one more thing in keepalive time that the extra workers that we have made, T3, T4, and T5, how long will they live? So let's say if I pass 10 in it, and my other unit was time unit, this is the same time unit, and I pass seconds in time unit.

  221. Speaker 2

    So I want to say.

  222. Speaker 1

    That my T3, T4, and T5 will stay alive for 10 seconds if they are idle. If they are not performing any work, they are standing idle, then after 10 seconds they will be removed and in our pool, only T1 and T2 will remain, i.e. two threads will remain, two workers will remain. So maximum pool size, We can make it temporary. That we have increased the threads but for limited time. We can reduce our threads again if we have added a quantity in keepalive time. If we have added a number like 10. And in time unit, its time unit second, millisecond, whatever is added.

  223. Speaker 2

    Okay.

  224. Speaker 1

    Now let's see the rule. How our threads will be created, how our pool will be created, etc. So first of all, this is our pool. This is our queue. Of some fixed length. And let's say we discuss the rule.

  225. Speaker 2

    Below.

  226. Speaker 1

    So rule. So let's see the limitations. Current pool size is 2, maximum pool size is 5. So let's write it here. Current pool size is 2, maximum pool size is 5. And now see, until we perform any task, not a single thread is created here. Even the current threads that should be there are not there. So the rule says something like this. Let's say you performed a task. You gave a task, let's say runnable task, task 1. And here we ask if current thread, we have the current workers in our pool if they are less than the core pool size basically the current is called core so this should happen so what we will do is we will create a thread and execute the task.

  227. Speaker 2

    Something like this.

  228. Speaker 1

    As soon as we got task1, we saw that there should be 2 workers in core pool size2. So we made a thread t1 and assigned this task1 as t1. Let's make it a little smaller. Now suppose we have another task. Let's say task 2. What we will do is, our current thread is basically one thread. So it is less than our core pool size. So we will make one more thread. Let's say t2. So here we made one more thread t2. And we assigned it task 2. So t1 and t2 went to perform task 1 and task 2. So now our core pool size should be the same.

  229. Speaker 2

    Very good.

  230. Speaker 1

    Now comes the second condition. Now suppose we have another task, task 3. Now what we will do is, here comes else. This is the second rule. The if part is over. Else, if you have a new task, and both the worker threads are busy, and only two worker threads could be maximum, you can't make another one because the core pool size is hit. So you will see that our queue is empty. If it is empty, then put that task in queue. So else if queue has space, then put task in queue. Something like this So our task 3 may come here Let's assume that our T1 and T2 are busy Let's remove them from here And show something like this This is T1 and T2 This is T1 and T2 This is performing some work So a task 4 came in between We also put that here.

  231. Speaker 2

    So let's keep adding it.

  232. Speaker 1

    Let's say task 4, task 5, task 6, task 7.

  233. Speaker 2

    The size of our queue is also configurable.

  234. Speaker 1

    So for now, we have taken 5 sizes and filled 5 threads. Now suppose we have filled both the core pool sizes. Both the threads are busy. Our entire queue is also filled. Now what to do? Let's make it smaller. Let's write third else. Now we have to see if the number of threads is less than the max pool size So we can go up to 5, we have used only 2 threads till now The answer is yes So we will create a new worker thread T3 And we will ask it to perform the new task So T3 will start performing our task 3 So let's say T3 comes out from here And our task 3 starts performing So task 3 will move away from our queue So by doing this, we will go to our maximum size. Now suppose another thread comes, your task 9, then we will make another thread because we have not hit 5 yet, we have made 3 threads so we will make another thread, T4 will perform task 4, which will be the most initial. And then we will insert the task 9 in the skew. Because task 4 will go with T4, all of them will shift forward and the task 9 will be inserted here. Same if we have a task 10, again we will see that we have 4 tasks, we can make one more.

  235. Speaker 2

    We will make a.

  236. Speaker 1

    Task 5, we will shift all of them forward and insert task 10 here too. Now let's assume that a condition has come that your maximum pool size has also been hit, that is, you have made 5 threads, here I have removed T5 from here, right? All 5 threads are also busy, your entire queue is also busy, now what to do? Now finally you get 4th else. This is called reject the task. Reject the task completely. So these are all the conditions. I hope you understood it well. First of all, we will make our core pool threads. Once all of them are filled and started working and none of them came back after doing their work. Then we will start filling our queue. If our queue is also filled, then we will make our maximum threads that we can make. If our queue is also filled, then we will reject any task. But there is a very high chance that one thread will come back. This is a very extreme case to talk about. All the threads are so busy, everything is busy. Our entire executor, our entire queue is filled. We are talking about that case. But generally some thread comes back to work. And it starts performing by removing things from this queue. Interestingly, the benefit is that no matter how many tasks you get in parallel, our maximum concurrency can be of 5. That means we can perform 5 tasks at a time. If we get more threads, we will put them in the queue. If we get more than that, we will start dropping them. We will not bring more concurrency in the system. That means I know the limits of our system. So if you give me a task to perform in bulk, then also my system will handle it in a limited way. It is possible that some tasks will be rejected, but my system will be up all the time. Let's quickly see an example of this in a code. So again we have taken a file called demo-photo.java and we have to make our own thread pool, thread pool executor. So now we are not going to write it like this. We used to write executor service executor equal to and we used to bring a new fixed thread pool from the executors class.

  237. Speaker 2

    And we used to put a thread here.

  238. Speaker 1

    We used to say that it will make everything from inside by itself. We don't need to work but no. Now we will make everything from inside. So we are going to make our own thread. ThreadPoolExecutor. Let's call this as Executor. Equal to new ThreadPoolExecutor. Let's bring this to a new line. So that we can see all 5 things. So now we have to fill all these 5 things. So first of all corePoolSize will be 2. MaximumPoolSize let's take 5 with our example. KeepAliveTime let's say I say 10. What is 10? So I have to give unit. So I take timeUnit.seconds something like this. I will write everything in a new line so that you can see everything. CorePoolSize is 2, MaxPoolSize is 5, KeepLifetime is 10, Unit is seconds. And I can also tell you the work queue. How should my queue be? It should be of limited size or unlimited size.

  239. Speaker 2

    Again, it has some names.

  240. Speaker 1

    So I will tell you its name later. For now, we will discuss its name. For now, I will make an array blocking queue. ArrayBlockingQueue and its capacity let's say 5. Something like this. Now what is ArrayBlockingQueue?

  241. Speaker 2

    We will discuss it later.

  242. Speaker 1

    But here I have made an entire Executor. Now let's perform some tasks. So let's perform the same task. 5 tasks int i equal to 1, i less than 5, i plus plus.

  243. Speaker 2

    Something like this.

  244. Speaker 1

    And here we will write less than equal to 5 i + + every time we will take a task id task id will always be i and we will not do anything, what we did earlier, executor.execute here we will give a lambda expression, don't take any input and what we have to do in output, we have to print let's say system.out.println so task sorry task plus task id i.e. task1 task2 isPerformedBy and here we will print our thread.currentThread.getName something like this.

  245. Speaker 2

    Right? We did this earlier too. Let's do one thing.

  246. Speaker 1

    After printing this, let's sleep it for some time. So that all the threads take some time to execute. So let's sleep thread.getName for 2 seconds. And then we wake it up. catchException Something like this. So every thread will take some time to execute. And finally, when our work is done, you know what we have to do? We have to shut down our executor. Executor.shutdown So the code in which I didn't do it, it's your job to shut it down.

  247. Speaker 2

    Remember that.

  248. Speaker 1

    So we made our own thread pool executor, defined its constructor, made 5 tasks, and performed those 5 tasks. You know what is the maximum core pool size? 2. And the maximum pool size is 5.

  249. Speaker 2

    We have made 5 threads.

  250. Speaker 1

    That means we can execute maximum 5 threads in one time. But let's see how many we can make. I have taken 2 seconds time here. It will take 2 seconds for every thread to work. So generally what will happen? Our first task will come. Basically i equal to 1 which will be our first task.

  251. Speaker 2

    It will come.

  252. Speaker 1

    So it is possible that even in executor if there is no thread then first a thread of core pool size. Since the core pool size is 2, one thread will be T1 and that task will be performed. Then a new task will be T2 and another thread will be T2 and that task will be performed. Then a new task will be T3. Now our core pool size is 2, so we will put it in Q. Then we will put T4 and T5 in Q. There are 5 capacities of Q. Let's reduce it to 2. So, we will keep our queue capacity of 2. So, T3 and T4 will be in queue. If by then, 2 seconds are over, that means our task 1 and task 2 will be performed, then they will come back to do task 5. But if it is not done, then we will make a new thread, T3, which will be the latest task, which will be task 3.

  253. Speaker 2

    This task is ID 3.

  254. Speaker 1

    Now, because 3 and 4 were in queue, now 3 got a thread to work, worker thread 3. So we will move 4 forward and insert 5 in the queue. So there must be some movement in this way. So let's print and see what happens. So here 3 tasks 1 performed by thread 1, 2 performed by thread 2, 5 performed by thread 3 and then 4 performed by thread 1 again and 3 performed by thread 3 again. That means 3 threads combined to.

  255. Speaker 2

    Perform 5 threads.

  256. Speaker 1

    Okay, I hope you understood how we made our own thread pool and how it performed. But interestingly, we don't make our own thread pool to a great extent. It's very rare that we define everything by ourselves. What do we generally write in code? We write something like this. We write, as we had written earlier, executor service execute. Let's call it executor2 because it is made on executor. Equal to, we use utility class executor and write new fixed thread pool.

  257. Speaker 2

    And here we pass the number of threads to pass.

  258. Speaker 1

    And the rest, this new fixed thread pool, it makes this thread pool executor from inside itself. It has a maximum pool size, it has its own keepalive time, it uses its own blocking queue. It will monitor everything by itself. It just tells us that we don't need to configure all this and we don't have much work to do. So just tell me how many number of worker threads do you need? We will tell it and it will perform its work. If we need a lot of configuration control, like if we want to see which queue should be, how much time should be alive, what should be the maximum pool size, then we can make it ourselves. Otherwise, this one is enough. Now let's see how many types of queues we have. The blocking queue. So, types of queue. See, mainly there are two types. One is our array blocking queue. This is of fixed size. Just like we made our new array blocking queue. So it takes the size in brackets in our constructor. So let's say we made it of 5 sizes. So this will be a queue of 5 sizes.

  259. Speaker 2

    Like 1, 2, 3, 4, 5.

  260. Speaker 1

    Right? According to this, it is of fixed size. And the second is our Linked Blocking Queue.

  261. Speaker 2

    Okay?

  262. Speaker 1

    Linked Blocking Queue. Now, because you must be able to understand the name from the inside. This uses the link list and this uses the array. Right?

  263. Speaker 2

    Linked Blocking Queue can also be infinite. Right?

  264. Speaker 1

    You can say that my Blocking Queue is infinite. It has multiple links attached to it. You don't have to think about the links from the inside. You just assume that it is a queue.

  265. Speaker 2

    Okay? But the more tasks you put in it, the more tasks you will keep putting in it.

  266. Speaker 1

    No task will be lost. So, this becomes your infinite. So this can be scaled to infinity But again, as I told you earlier, we generally use our executors class, which I told you is a utility class. There are a lot of threadpools already made in it, like one is a new fixed threadpool. And you know that our basic threadpool executor, which we were still making by ourselves.

  267. Speaker 2

    Apart from this, there is a cache threadpool.

  268. Speaker 1

    This is a different type of thread pool, we will discuss about it later. But in this, multiple types of thread pools are already made. We just have to use them directly. Now, let's see what are the thread pools in executors and what they do. First of all, this is obviously a fixed thread pool. Now see, I told you that it uses the ThreadPoolExecutor from inside And we just tell it how many number of worker threads we need But other things it configures by itself So I will tell you what it configures It says, I know what I will configure Fixed number of threads plus unbounded queue means I will use an infinite queue. By default, when we make a new fixed executor thread pool, it uses an unbounded queue from inside. We can put as many tasks as we want in it. Because of this, sometimes there can be a memory issue. Because what did you do? You made the number of tasks infinite. Memory issue. Apart from this, we have a very famous cache thread pool. Now, this is the opposite of the above. It says, I will use unlimited thread plus no queue. I will not use any queue, I will leave null in queue. What does unlimited threads mean? Basically, the pool of this, whenever you have a task, it will create a new thread for it and will ask the worker to execute the task. Again a task came, a new worker was created, it was asked to execute the task. So the more tasks you will give, the more number of these workers will be created. So basically, here we say threads are created on demand. And its keep alive time is 60 seconds. After 60 seconds, your threads start dying. This is its idle time. But still, it consumes a lot of memory.

  269. Speaker 2

    Cache, thread pool.

  270. Speaker 1

    Everything starts to cache. Basically, it starts to put the expenses in a new thread. Sometimes it can be very useful if you have a bulk amount of traffic coming and you have to handle it. But you think, sometimes it can be disastrous if a lot of traffic comes and you have made so many threads.

  271. Speaker 2

    Then your whole system will be slow.

  272. Speaker 1

    Apart from this, One is the single thread pool. You must be understanding this by its name. It has only one thread, one worker thread. Internally, it also uses a queue. Now look, since it has only one thread, all the tasks do the same thread. So let's say this is your pool, this is the same thread, and this is its queue. Internally, it uses a queue. Obviously, if you have a first task, it will execute this T1 thread, the worker thread. After that, any task that comes will go to your queue. And as soon as it executes T1, it will execute a task again. And when it returns, it will execute a task again. In a way, it will execute all the tasks one by one. This makes all our tasks serializable.

  273. Speaker 2

    What does it do? It serializes them.

  274. Speaker 1

    So, if you were thinking of executing everything concurrently or parallelly, it will say that it will only go through one thread at a time from the funnel or pipe.

  275. Speaker 2

    When will this be useful?

  276. Speaker 1

    This is useful for very specific requirements Like if you are making your own logging system And you want all the threads Or basically all the requests in the threads To be registered one by one And you don't want anything to get missed or wasted So you can use single thread pool in it It makes it very serialized, it performs only one task at a time So we saw fixed thread pool, cached thread pool, single thread pool One is called schedule thread pool.

  277. Speaker 2

    So, Scheduled Thread Pool.

  278. Speaker 1

    Which is this Scheduled Thread Pool? The hierarchy we saw, basically this one. We saw the Thread Pool Executor, this is Fixed Thread Pool. This is Scheduled Thread Pool. We will talk about Fork Join Pool in the next video. But this is our Scheduled Thread Pool. This is very interesting. What can it do? It can schedule your task to run in future So basically run task in future It has a special method So if you make a scheduleThreadBull So let's say it's name is Executor and let's say it's called scheduler Because we can schedule it So you made a scheduleThreadBull whose object name is scheduler So it has a method called.

  279. Speaker 2

    Schedule.

  280. Speaker 1

    Schedule And give a runnable object in it. Let's say you gave a lambda expression. You said no input. And do one thing. Just print in the screen. System.out.println Let's say hello.

  281. Speaker 2

    Just this. Okay.

  282. Speaker 1

    So this is your lambda expression which you passed. Apart from this lambda expression, you pass a time in this function. Let's say you wrote two.

  283. Speaker 2

    Two unit.

  284. Speaker 1

    And this time's unit. So you wrote let's say time unit dot seconds. And then you close it. So you have passed three parameters on it. One is the lambda expression in this function. One is the time unit. One is the time and the third is the unit. So it says that this task, which you have written, hello, perform this task after two seconds from now.

  285. Speaker 2

    Okay. So you have scheduled your task in the future.

  286. Speaker 1

    Apart from this, it has another interesting method which is scheduler.

  287. Speaker 2

    ScheduleAtFixedRate Right? What does this say?

  288. Speaker 1

    It says that take a lambda Let's say I'm showing it empty for now Here I took a lambda expression After that you give me the initial time 0 Give me a fixed rate, let's say 2 And give me a time unit So again I write, let's say TimeUnit.Seconds Okay? Something like this Something like this This is different, this is different Now you must be understanding the term schedule at a fixed rate. You want to schedule a task for the future which will happen at a fixed rate every time. So let's say this will happen for the first time at 0th second and after that it will happen every 2 seconds whatever you have given here. Schedule at fixed rate. So, this is your schedule thread pool. Again, you can make it internally if you want. But, we generally use our executor's schedule thread pool. If we want to schedule some tasks, then we have. schedule and scheduleAtFixedRate method. We can use this to schedule tasks in future. Now, your job here is to write all the theories and thread pools that we have read and use them by writing good code on them. We have written the basic code of all of them. You go and expand this code and experiment a little bit. Make an object of scheduled thread pool and schedule the task in the future at a fixed rate etc. You will get to learn a lot because it is very theoretical. So many things are not going to enter your mind. I will provide you the notes as I told you. Apart from this, there is one last topic. After that, we will finish this lecture.

  289. Speaker 2

    And that is, suppose this is your thread pool. This is your queue.

  290. Speaker 1

    And what did I say? Your thread pool is also finished. Maximum thread has been created. And this is also full. After that, if a new task comes, then what happens to it?

  291. Speaker 2

    Right now, I said it straight. We will abort it. We will skip it. We will leave it. But we say this.

  292. Speaker 1

    Rejection policy Red rejection policy And it can be multiple It's not necessary that we reject it every time There is one by default If you don't make policy by yourself Then by default We have abort policy Abort policy What does abort policy say? That if there is any rejection Then throw an exception directly And that exception's name is Rejected execution exception Okay Throw this exception.

  293. Speaker 2

    Rejected execution exception.

  294. Speaker 1

    Exception, throw this exception and this exception will tell that we have rejected this task because we did not have space available. Apart from this, there can be many more policies. The main one is a discard policy. Discard This is very simple. It says to silently discard. Silently discard. Don't perform any task, just leave it.

  295. Speaker 2

    But this is a bit dangerous. Because we never know that our task didn't perform.

  296. Speaker 1

    Right?

  297. Speaker 2

    So basically, data will get lost.

  298. Speaker 1

    And the most used one is Discard oldest.

  299. Speaker 2

    Policy.

  300. Speaker 1

    It says, remove the oldest task from your queue, discard it, and add a new task. Discard oldest policy. So this is the most used policy. We use it in the real system. We discard the oldest task and add a new one. We don't like to silently discard it because it causes data loss. And abort policy is also useful sometimes. But what will we get by giving an exception? We want to get it done somehow. So we throw rejected exception only in some cases. So I hope you understood the rejection policy. We talked about multiple executors, right? Among them, this was our fixed thread pool, this was our cached thread pool, and the most interesting was our scheduled thread pool.

  301. Speaker 2

    We used the fixed thread pool and wrote the code.

  302. Speaker 1

    Now your task is to write the same code for cache, single, and scheduled thread pool. In cache and single, all the methods are going to be the same. The only difference is how you work from the inside. In cache, we use unlimited threads, so all your tasks will be performed in parallel. It will never happen that no task can be performed in parallel because as soon as you give a task, it will make a thread. But if you give a lot of tasks, you will have to make a lot of threads, so the context switching will be too much and your system will be slow. And the single thread pull will serialize all your tasks. So if you write a code of this, then you will see that if you had made 100 tasks, then those tasks will run one by one. What you have to do is to take a time of 200 milliseconds or 300 milliseconds between them. So first task 1 will be done, then task 2 will be done, then task 4 will be done, then task 5 will be done, etc. Order doesn't matter, but these tasks will perform one after the other, never two tasks will perform in parallel.

  303. Speaker 2

    And finally, you have to create.

  304. Speaker 1

    Your own scheduled thread pool, in which you have to schedule a task in the future. Write schedule and time unit in it, let's say schedule after 3 seconds. And that task will be scheduled after 3 seconds.

  305. Speaker 2

    So these are different types of thread pools.

  306. Speaker 1

    We have learned the thread pool executor from inside, which is our basic thread pool.

  307. Speaker 2

    We learned to use the scheduled thread pool.

  308. Speaker 1

    Now in the next class, which is going to be the last class of Java, we will see what is our completable future and what is the fork join pool and we will learn more about our virtual threads.

  309. Speaker 2

    Again, you should not miss that lecture at all. It is the last lecture of Java.

  310. Speaker 1

    It is a very interesting lecture of multi-threading and it will complete your entire multi-threading knowledge. lecture. See you in the next lecture. Till then, thank you so much.