Java Multithreading using Executors Framework | Arun K. | Skillshare

Java Multithreading using Executors Framework

Arun K., Technical Architect and Software Engineer

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
10 Lessons (1h)
    • 1. Creating Threads Using the Threads-API | First Way

      10:25
    • 2. Creating Threads Using the Threads-API | Second Way

      4:27
    • 3. Creating Threads Using the Threads-API | Third Way

      4:32
    • 4. Creating Threads Using the Threads-API | Fourth Way

      3:50
    • 5. Creating Threads Using the Threads-API | Fifth Way

      3:54
    • 6. Executors Framework Overview

      4:05
    • 7. Important Interfaces and Classes in the Executors Framework

      10:36
    • 8. Creating Threads Using Executors Framework - Fixed Thread Pool

      10:32
    • 9. Creating Threads Using Executors Framework - Single Thread Executor

      3:09
    • 10. Creating Threads Using Executors Framework - Cached Thread Pool | Part - 1

      5:27

About This Class

fe566002

The class covers all the concepts of Executors from scratch in combination with parallel concepts of the Threads API.

  • Do you know how to return values using the normal Threads API and its Runnables?
  • Do you know the various ways of terminating threads midway for both the APIs?
  • Do you know how to 'join threads' using Executors?
  • Do you know that you cannot catch stray exceptions leaked out from a thread by using try-catch block - neither in the Threads API nor in the Executors one? And that this can lead to third-party code killing your scalable, high-performance and high-availability enterprise application?
  • Do you know how to check if a task has finished execution using both the APIs?
  • Do you know what are daemon threads and how to create them using Executors?
  • Do you know how to name Executor threads?
  • Do you know the various ways to schedule tasks for running in future using both the APIs? Do you know the various 'types' of scheduling?

If the answer to any of these questions is 'no', then this course is for you (provided that you know Java and the basics of multi-threading already)!

What are you going to get from this course?

  • Over 50 lectures and 7.5 hours of content!
  • The Source Code of all the examples!
  • Confidence to move away from the old Threads-API and use the modern Executors-API for all multi-threading needs instead.
  • Exploit the Ninja Techniques learned from this course to write safe and error free multithreading code in the first iteration itself.
  • Understanding how to exploit the various pro techniques to avoid the pitfalls while using Executors.
  • Understanding how to leverage the similarities & differences between the Threads-API and the Executors-API.
  • Rightly judge which Executor pool to use for which needs.
  • Differentiate between safe and error-prone multi-threading code.
  • Appreciate the reasons why Executors API was built even though the Threads API already existed.
  • Write efficient multi-threading code by utilizing a plethora of pro tips and techniques

What is the target audience?

  • This course is meant for all Java professionals who are familiar with Java's Threads-API but who are not comfortable with the Executors-API yet. For example - if you know how to terminate normal threads but not how to terminate Executor tasks or threads, then this course is for you.
  • Even if you do not know how to terminate normal threads, return values from normal threads and the like - then also this course is for you. Professionals who are still using the old Threads-API and want to have more practical knowledge about some advanced concepts of this API can also benefit from this course as Threads-API is also covered in detail.
  • If you love to have deep knowledge of underlying concepts of a technology or topic rather than just shallow familiarity, then this course is for you.
  • This course is probably not for you if you are looking to learn about Java multi-threading from scratch! You should already know about the basic concepts of multi-threading viz. what are threads, why are threads required, various states they can be in, what is synchronization, what is locking, etc.
  • This course is definitely not for you if you do not know how to code in Java!

Transcripts

1. Creating Threads Using the Threads-API | First Way: Hey, friends. Welcome to Section two off the course titled Efficient Job, a multi trading with Execute er's using executors to do everything that you can do with threads Before beginning our journey on the scores, I would like to congratulate you first for making the decision to invest in yourself. Knowledge is power, they see. I hope this course proves useful to you as per your expectations. So let's play as this is the first technical section in this course here, we will start from the basics and just discuss how to create and run threads using the to a P A's. Now, whenever you want to create and run a thread in Java, the basic mechanism is always the same. No matter what a p a you use, you always need to do three things. Number one. You need to have an instance off thread Class number two. You need to have an instance off rentable interface implementation that has to be provided to the threat class object and number three. You need to call the start method on the thread object to start the thread as a separate sequence off execution inside the give'em. Now let us first look at how to use the threads FBI here. Afterwards, we will discuss the execute er ze p a. There are a few techniques to create and run threads using the threads A p A. And all those techniques differ only in Dewey's number one, the baby create the threat class object and the rentable implementation and number two. How do we provide the rentable object to the thread class object so that a separate thread off execution can be spawned and the task can be executed in that All right, time to look at some court. Now here is the first way of creating threads using the threads. FBI I have already created a new project called Efficient Multi Trading. Inside this project, I have created a class first week that has an empty public static white main method inside it. Now, a thread by definition drives our task in an independent flew off control or a threat off execution. Therefore, we need two things. A task definition and a thread. So I am creating an inner class here by the name off First task that extends the thread class thread, in turn, already implements rentable interface, so we can override the run method in this class to provide the task definition toe this thread. Now, as part of the task definition, I'm just going to print a statement 10 times inside a loop. Now we need to call the start method off the thread class. Also, in order to start the third off execution for this example, we're going to call the start method in the constructor off first task. So let us create a constructor here with this court. As soon as we create an instance off the first task class, the start method off the thread class will be called from within its constructor. This will start the thread immediately. So let us create our first thread by creating an object off this class in the main method off the first week class. I'm now going to run this class as a job application. You see that there is also a shortcut. All shift X N g for running this class. The next time I'm going to use this shortcut, the threat has run very fast. We could not even see it running, So let us introduce a small delay in the loop here. So that we can witness the results coming in the console one at the time. Our daily off 200 milliseconds should be sufficient now. I'm pressing control shift Oh, so that they import for time Unit automatically comes in. The sleep method here throws an interrupted exception, which is a checked exception, so we need to surround it with a cry catch block also, and let us put 26 outs in the main method also so that we can distinguish when the main threat starts and ends. And when the spawn thread in which the first ask executes, starts and ends buttoning this last now there. The output was a little slower this time, and we could see the individual six hours coming on the console from the output. We see that that first, the main threat starts, and then it spawns the second thread and before the second thread could get the CPU to execute, the main thread ends. After that, the spawn trade executes and prince the countdown messages one by one. Now what if we want to spawn a second thread as well? For that, we just have to create another object off the first task class. This will create a new task as well as a new thread, and then start executing the task in that thread, and by the way, you can also capture the thread reference here while creating the instance off. First task. If you captured the thread reference, then you can do all sorts off things with it. Later, you can rename the thread, join it, check if the threat is running or has finished etcetera. We will cover all these things in detail in the subsequent tutorials. Now, if we are running to tasks in parallel, then we also need to identify from which of the two tasks each off the tick tick output in the console is going to come, so we need to provide an identity to each task and print its identity information also along with the tick tick messages. So let us do that. Here I have created a static integer variable count and a private indigent variable I d. This idea will be the identity off the task. Every time a new instance of this class is created, we are implementing count by one and then assigning the resulting value toe the I D variable so each new task instance will get a new I. D. Let us also print this idea and this is ouch! Let's run this class again. Here again, the main thread starts first and then it's ponds. The other two threads. The first threat gets the CPU and it prints Dick kicked in. And after that, the main thread ends and then the two threads continue running till they finish their natural course. In reality, you do not know which thread is going to get the CP when so you won't get the same output. Every time you run this program, the output will be similar, but not exactly the same. So in this method, off creating and running threads, the thread object and the rentable implementation both are provided by the same class. In our example that glasses first task. In order to start the thread, the start method is invoked from the constructor of the first Ask itself. So as soon as you create an instance of this class, the thread also starts immediately. This brings us to the end of this tutorial. See you in the next video. Now till then, take your and by 2. Creating Threads Using the Threads-API | Second Way: Hello, dear friends. Welcome to the second video in the series efficient job market trading with Execute ER's. In this video, we will discuss about the second technique for creating and running the threads using the normal threads FBI Now, in order to remember the new concepts and have a good understanding off them. It is best if you can build new knowledge on top off existing knowledge that is, to gain new knowledge in continuation off existing knowledge. So you will see that in many off my future tutorials in this series, I will copy an existing class developed in one of the previous tutorials and then modify it for explaining the new topic at hand. This will help the learner to connect the current topic with the past one and therefore build the new knowledge on top of that. So for the current court example, we're going to create a new class second way by copying the first way class that we developed in the previous tutorial. And I'm also going to split the editor area into two so that we can see the two classes side by side and see the differences between them and also removing the Project Explorer view from site here Now the first thing to be done in the new classes to rename the inner class first task toe Second ask. I did not use the refectory functionality here because Eclipse gets confused and tries to rename the inner class in the first way class toe, which we do not want. So I just did a find and replace, which was good enough for our current scenario moving on. Now the only difference between the previous technique and the current technique is that we're not going to start the thread immediately. As soon as the instance off Second task is created. So I'm going to remove that this start start statement from its constructor. So how do we start that red now? We can call the start method on the second task object. It extends a thread class and therefore inherits the start method also, So let's do it for the second instance off. Second Task. We had used Polymorphism in the previous tutorial and already captured its reference in a threat type variable d. So to start the second thread we have called start on that variable only, Let us run it now it has similar output as our previous tutorials because we haven't changed anything in the task definition. That is the run method here. Looking at it, the main threat started and then spawned the two trends. After that, the first threat got the CPU and printed its 1st 6 out tick tick 10. Then the main threat ended. And after that, the two threads ran side by side in parallel and printed their outputs. And after running their due course, the finished. So the only difference between the first technique and the second technique is that in the second technique we start the thread from outside rather than the constructor of the thread come task definition. This technique gives more control to the calling code as to when to start the thread. With that, we have come to the end of this tutorial. See you in the next video. Now, till then, happy coding and by 3. Creating Threads Using the Threads-API | Third Way: Hello, friends. Welcome back to another session on creating and starting threads using the normal threads. Eh, P A. In decision, we will discuss the third technique for the same as the third technique is similar to the 1st 1 I'm just going to make a copy off the first way class and create a new class called Third Way. Let us also keep the first way class in a second editor here to see the differences between the first technique and the third technique before moving further, let us rename the first task in her class here to third Task the first way. And thirdly, classes are still the same as off now, we will now start making changes in the third grade class that show the difference in the two techniques. The first change that we're going to make in the third way class is in our thread come task definition that is in the inner class. Third task instead, off extending the thread class, we will make it implement the rentable interface as this class no longer extends threat. Now we do not have access to the threads. Start mattered in this class, so we need to remove that this not start statement from its constructor and lastly as the third task class does not extend the threat class. Now we cannot capture the thread reference in the main method any longer. These updates have changed the third task class from being a thread come task definition toe only a task definition now. But in order to run a thread, we also need a thread object in addition to the rentable implementation or the task definition. So what we are going to do is that we will create a new tread object in the constructor of the third task and positing object off the third task itself as dusk definition. We're going to use that this reference here. Then we're going to start that thread immediately. So let's do it here. We have used the overloaded constructor of the threat class that takes a rentable parameter . Our updates are complete. Let us run this class now again, we have got similar output as the previous two tutorials. The reason being that our run method has exactly the same court, even if the threads are started in different ways. In all the three examples in the end, there are three differences between the first technique and the 3rd 1 Firstly, in the third technique, we have a task definition. Instead, off a thread come task definition, that is our third task here implements rentable instead off extending thread. Secondly, to fulfill our requirements off a thread object, we're creating the thread object in the constructor and providing it that this reference before starting the thread immediately. And thirdly, we can no longer capture the thread reference in the main method. In fact, there is no way here that the caller can capture the thread reference at all. So this third technique is useful in those scenarios where you need fire and forget type of threads. That is when you do not want to carry out any operations on the threads. Once they have started, you do not care what happens to them once you have started them, whether they finished successfully or they take a long time to complete or the finish ready fast, etcetera, etcetera. This brings us to the end off this session. Hope you found it interesting. See you in the next decision. Now, by 4. Creating Threads Using the Threads-API | Fourth Way: Greetings, dear students, and welcome to this video where we will look at the fourth technique for creating and running threads using the normal threads. FBI as the fourth technique is similar to the 3rd 1 So we're just going to make a copy of the third way class and create a new class called forth Way. Let us look at Fort Way and Third way side by side. We also need to change the name of the third task tow fourth task. Now come the actual updates in this class that will reflect the differences between the fourth technique and with her technique. Firstly, we're going to remove this line from the fourth tasks Constructor. So now the thread is not going to be instance created and started from the tasks constructor. Instead, we're going to do everything related to the thread class. In the main method, that is, we're going to create instances off thread class, provide them the task objects and then started threads from the main method itself. So let's do it. And by the way, we can also capture the thread reference if we want. As we have full access to the thread objects from the main matter. Now, after capturing the thread reference, we have called the start method on that reference itself to start the second thread, the glass is ready to run now. Once again, we have similar output as over previous three tutorials because the corelogic off the task is exactly the same. So the only difference between the third technique and the fourth technique here is that instead of creating the thread object in the tasks constructor, we're creating it in the main method outside the constructive. This has also allowed us to capture a reference to that threat object, thereby enabling us to manipulate the threads behavior in the in the future if required. Lastly, the current technique is the most used technique for creating and running threads because off two reasons. Firstly, here, the task definition is entirely isolated from the thread related code, so such tasks are also amenable to be executed by the executors. In addition to normal threads, we will see how to do this in the later videos. The second reason is that this technique allows for a greater control on when to just create the threads and when to actually run them most of the tasks in rest of the videos in this course use this technique only for demonstrating the concepts. And that's it for decision. This was a small one. See you in the next one now by 5. Creating Threads Using the Threads-API | Fifth Way: Greetings, folks. And welcome to this tutorial. In this tutorial, we're going to discuss the fifth technique for creating and running threads using the normal threads. FBI. I have already created a skeleton class here by the name Off Fifth Way, in which there is a main method with 26 outs signifying the start and end of the main thread. I have also opened the fourth way class here that we had developed in the previous tutorial . Now, this is a quick and dirty technique. In this technique, we're going to use an inland task definition by using an anonymous implementation off. They're unable interface. We will provide this definition toe a trend object and then invoked the start method on that thread object. Let us see how to do it. No. As part of the main logic off the task, we are going to use the same court that we have used in the previous examples. So we're just going to copy it from the inner class Fourth task In the fourth week, class and anonymous implementation cannot be reused. It is going to create a single object off the implemented class only, so there is no need for the identity here. Let's remove it from the CIS out now to start the thread, we can call the start method directly on the thread. Instance in the same statement itself like this, and this completes the glass. Let us run it now. So nothing special about this output. We spawned a single thread. Only the main threat starts first, then spawns that thread, and then the main thread ends here. After that, the spawn thread gets the CPU and executes so in the fifth technique, as opposed to creating a separate reusable task, we have provided an inland task toe the thread object and started it there itself. However, no one is stopping you from capturing the thread reference here. If you want, there's same output. This technique is mostly used to handle you events in applications that obviously have a user interface to handle you events, you do not need to create multiple instances off a task at a time. Instead, whenever and event occurs, a task object is generated from the in line definition and is used there and then to handle the event. That's all I had for this tutorial. Hope you enjoyed watching it starting from the next one, we will discuss how to create and run threads using the Execute er's FBI build in take care and by 6. Executors Framework Overview: Greetings, folks. Till the last video, we saw how to use the threads a p I to create and run threads. Starting from this video, we will learn about the executors framework as discussed in the first video in this section . In order to create and run a threat off execution, we need to have a thread class object and a task definition. And then we need to call the start method off the thread class to start the thread. There are multiple ways to create and start threads using the threads. Eh? P A. However, when we use the executors framework, our job is made much easier. There is technically only one way to execute a task in a separate thread off execution here . We just need to write code for defining the task that we won't run in a separate thread and provided to an executor service, and that's it. The executor service automatically creates the thread and runs over task in that thread for us, without us having to create a threat, object and started execute Er's are the preferred way off executing tasks since Djelic, a 1.5, they optimize multi threading capabilities off Java and improve the applications efficiency through optimal utilization, off resources that can also be tuned now. Thread creation has some amount off CPU overhead. It is wasteful if we have to create a new thread every time we need to execute a task. That is why execute ER service uses thread pools internally, in which the threads are recycled and reused in some of the execute er's. The threads are also allocated up front if required. They can also be started at the time off Execute er creation itself. All that is required to do now is to provide one or more tasks to the execute er for execution. In this way the executor Framework de Couples. The task submission from thread creation and management process. Now each thread in the pool after executing a task, picks up the next task from a task you and executes it. The threads continue to do so till the Q becomes empty. After that, the threads just block on the task you and wait for more tasks. Once all the tasks are executed or the application is going to be shut down, you need to tell the executor service that its services are no longer required by calling its shutdown method. This will shut down the executor service and it will stop accepting any new tasks for execution. All the tasks that were currently executing will continue to execute till completion. All the pending tasks in the queue will also be executed if required. You can instruct the executor service to interrupt all the running tasks to this can be done by calling its shut down now method. In this case, it will also not run depending tasks. In light off this discussion, we can see that there is only one way off creating and running threads using the executors FBI here you first create a task definition by implementing the Run Able interface or the callable interface. And secondly, you get hold often execute er service and passed the task object. Do it for running. After we're done using the executor service, we can stop it after stopping it does not accept any more tasks for execution. That's all for this video. See you in the next video. Now by 7. Important Interfaces and Classes in the Executors Framework: Hello, folks. In the previous session, we had an overview off the executors framework. In this session, we will discuss about some important interfaces and classes that frequently appear while using the executors a p a. The 1st 1 is the Execute ER, which is the main interface in this framework. Its main purpose is to decouple the task submission step from trade creation and running steps. It has only one method wide execute that takes a reasonable as a parameter execute. ER service is the second most important interface in this framework, and it extends the execute er interface. It provides a life cycle to the execute er's, that is, it provides for an initialization phase, a service fees and a destruction fees in the initialization face. It locates the required number off threads and starts them too. If required, this phase is usually hidden, and you can just customize it by providing it some parameters through executors class that actually bootstraps the service in the service phase. It provides its services by running the submitted tasks in the destruction phase. It shuts down and stops accepting new tasks for running the box on the right shows. Some of the methods provided by the executor service interface. The top two methods are the service methods, these two overloaded methods except a callable and a rentable respectively, and run them. We already know about rentable for Java newbies regarding the callable, we call a task by implementing the callable interface when we want that task to return a value. A reasonable, on the other hand, does not return any value. Also note that as the executor service extends the executor interface, the execute method is also available for use here. Now. The last three methods shown here cater to the destruction fees. With the shutdown method, you can instruct the service to shut itself down. After this method is called, no new task can be submitted to the service for running. Whatever tasks were being executed by the service will keep running till finished, and whatever tasks were pending to be executed will still be executed. Only new tasks will not be accepted. If you try to submit a new task to the service after shutting it down, obviously you will get an exception. The shutdown now method, on the other hand, is a little unforgiving. It attempts to stop all the actively executing tasks and also holds the processing off all waiting desks. It also returns the list off pending tasks that had not yet been run. You can check whether the executor service has indeed shut down or not by calling the is shut down method on it. The next entity in this light is the executors class. It is a factory class that constructs and returns various kinds off instances off the executor service with commonly useful configuration settings. As is clear from the methods shown on the right, The returned executor service instance can act as a fixed threat pool on a case threat pool or even as a single thread, execute ER for creating an executor service backed by a fixed threat pool. You call the new fixed thread pool method. It takes an indigent parameter named and threads that specifies the number of threads that you want in the pool. This means that at any time at most N threads number off tasks can execute concurrently. Let me give you an example. Suppose that we have specified the value off in threads as five, that is. We want five threads in our pool, then This means that at most, five tasks can execute concurrently. If we submit, see 20 tasks toe the spool than the 1st 5 of them will start executing immediately in parallel, while the rest of the 15 tasks will be put in a task you. Whenever any of the five threads finishes execution off the task that it was executing, it becomes available. It then checks if there is any dusk awaiting execution in the task you If there is, it takes the next task from this Q and executes it and so on and so forth. But the number off simultaneously executing tasks will never exceed five. Here. You can also create an executor service backed by a case threat pool by calling the new case threat pool method. This kind off executor service continues creating threads as long as no threat is available and there are still some tasks awaiting execution. Once a threat is done, executing a task, it is reused. If a threat is available when executing a task, then that thread is used instead off creating a new one. For example, suppose that we have submitted 20 tasks one by one, such that none of the tasks finish executing at least until all the 20 tasks have been submitted. Then this kind of pool will create 20 threads for running those 20 tasks. If we submit five more tasks and none of the previous 20 tasks have finished executing, then five more threads will be created to execute the newly submitted five tasks, thereby making the total number of threads and tasks as 25. Now suppose that four of the 25 submitted tasks have finished execution. This means that four threads are now available. If we submit five more tasks now, then four off them will be executed by the four available threads, and one new thread will be created for the 5th 1 So theoretically there is no upper limit as to the number off threads that will be created by this kind off executor service or pool . Such a pool is useful for scenarios where a large number off short lived asynchronous tasks are to be executed. After the case threat pool, let us know discuss about the single threat ex cuter. Sometimes you need a background thread that should execute tasks one by one from a que, but she would never execute more than one tasks simultaneously. For example, Java swings, even dispatch thread has such a requirement. It has to process and dispatch you events one by one from acute. For such requirements, there's the single thread executor. It can be created by calling the new single thread executed method off the executors class . It guarantees that all the tasks will be executed sequentially only, and no more than one task will be active at any given time. Similar to the single threat execute ER is single thread scheduled Execute ER that can be created by calling the new Single Thread Schedule executor method. It creates a single traded execute ER that can scheduled tasks from a cue to run one after the other after the given delay, or to execute the tasks periodically from a que after knowing about all these execute er's . One thing worth mentioning here is that all the execute er services after knowing about all the eggs after knowing about all these, execute er's. One thing worth mentioning here is that all the execute er service instances returned by the execute er's class are actually objects off a class called thread pool Execute er thread pool. Execute er implements Execute er service interface. Different kinds. Off thread pools are constructed by passing in different configuration settings to the constructor off the thread pool. Execute er class knowledge off. This class is not required for using the executors class or for even using the executors framework at all. You only directly need toe work with thread pool. Execute ER in rare instances when your applications needs cannot be fulfilled by the execute er service instances provided by the executors factory class. So just keep it at the back off your mind that if you need some custom thread pools, then you can create them by tweaking the thread pool. Execute er class. The last entity in the list on this slide is the future interface. Whenever you submit a callable for execution, the Executor service returns you an instance off future. You can call the get method on this future instance to get the value returned by your callable task. The call on this get method gets blocked till the task has run to completion and has returned. The value future also provides is done method for checking. If the task has run to completion as yet or not now, as discussed already, there are many types off pre tweaked thread pools provided by the J. D. K out of the box. In the upcoming videos. We will look at each of these thread pools in action one by one, except the schedule Execute ER's, which we will look at in another section later. We will also see the classes depicted on the previous light in action in the upcoming videos. That's all on the topic off important classes and interfaces in Execute Er's framework. See you in the next video Now still, then take your and go by. 8. Creating Threads Using Executors Framework - Fixed Thread Pool: Hi there. Welcome to one more video on the topic off creating and running threads. Hope you have been enjoying all the videos to allow. In this video. We will see how to work with fixed thread pool Execute er's as discussed in the previous video in fixed thread pool Execute er the number off threads is fixed in order to get an instance off. Fixed threat pool Execute ER you need to call new fixed thread pool method on a factory class called Execute Er's. The number off threads that we need in the tread pool is passed as an argument to this method. I have already created a skeleton class called Using Fixed Threat Pool that has a public static white main method with a couple of six outs signifying the start and end of the main thread. We also need one or more renewables that can be executed by the fixed threat pool execute er. So before beginning to put some chord in using fixed threat pool class, we're going to create a reasonable implementation with a class called Loop Task. A now looped ask a will be used in some subsequent examples as well, so I'm going to put it in a package named Dude. Start comin to show that it is a common class used by many other classes and packages as business logic off this task, I'm going to use what we wrote previously for the threads AP examples. So I'm just going to do a copy paste here from the fourth weight class. - I am also going to put in here some sis out with eye catchers for easy identification that will signal the start and end of the task in order to emulate riel world tasks more closely , let us also make the delay random by making the tasks sleep for random periods rather than fixed periods off 200 milliseconds. For this, we can use the math, not render method. This method returns a double value between 0.0 and 1.0. If we multiply it by 1000 we get values between 0.0 and 1000 because the sleep method works with long value instead off double. We also need toe cast this expression too long, so the task will allow sleep for a random period that lies between zero and 1000 milliseconds, and we are done with defining the task. There are no computation errors. I hope it runs. Let's implement the main class now. First of all, we're going to create a fixed threat pool execute er service here, like so, keeping the number off threads in the pool as three. Now this line that we have just added signifies the initialization. Phase off the executor service onto the service phase. Now time to submit some tasks to the service. Now tasks can be submitted by using the execute method of the executor service interface. Let us submit three tasks to the service for the time being. Running this last now from the output we see that all the three tasks had started simultaneously as we had all the three thread pools available to execute them a lot off context. Switching happens and each task gets a chance to run. So all the tasks run their course and in due time they all finish their business and and successfully, you can see that even though our tasks have finished, the program still has not finished. It is still showing this red I can hear meaning that the program is still running. Let me kill it forcefully by clicking on this Aiken. Now, why do you think the program did not end well as discussed in the previous video? We need to carry out the destruction phase off the executor service by calling its shutdown method running it again now similar output and our program has also ended, So never forget to shut down the executor service. Otherwise, it is going to cause a memory leak when you shut your application down. Moving on now What if we submit more than three desks? Let us try submitting six tasks running the program again. We see that only three of the tasks have started executing in the beginning. As soon as one of the tasks end, another one starts here. Task three has finished, and after that task for has started here. Task to has finished and then Task 500 lastly, past one Finished and Task six started and afterwards past 45 and six have also finished executing. But at all times, the total number of Kong currently running tasks never exceeded three. So what if we make the number of threads in the pool as six. Let us try that running it again. Now, as you must have guessed already, all the six tasks have now started and are running concurrently. This is because now we had six threats available in the pool at the beginning itself. Now, what if we try to submit a task after the service has been shut down? Let us try that too. Running it. Now we see that we have got a rejected execution exception on line number 25. This is as expected as the service had already been shut down. It did not accept accept any new tasks for execution. One last thing for the newbies before we end this tutorial video in this video, we have just submitted the same task multiple times for exploring the fixed threat pool. However, you can submit any number and any type of tasks that you want and they may do entirely different things compared to each other. The same holds true for all the previous and subsequent videos in this course as well. So don't get confused on this point. This brings us to the end off this tutorial. See you in the next video. Now where we will discuss Gauged threat pool, execute er's bill then but by 9. Creating Threads Using Executors Framework - Single Thread Executor: Hi there. Welcome to this video. In this video, we will explore the single thread execute er a single thread execute er is a special case off the fixed thread pool. Execute er here the pool size is set to one rest. Everything is just like the fixed threat pool Execute er but the pool size off one gives it some special properties as the usage off single thread execute er is similar to the previous to execute ear's that we have discussed in the previous videos. I'm just going to make a copy off the using cased threat pool and create a new class called using thread using single thread execute er keeping the loop task A also open here now, in order to get an instance off single thread execute er we need to call the new single thread executed method on the executors class. And just like the case thread pool execute er it does not take any argument and we're going to submit three tasks to this execute er for which the court is already there. We just need to remove the last three tasks. Submissions. Nothing else needs to be changed. So running it now we see that the first task has started executing, and when the first ask ended, the second task started executing, and when the second task ended, the 3rd 1 started executing. So a single thread execute ER with the pool size off. One essentially serialize is the task executions as at one time only one task is executed, no matter how many tasks there are in the queue. Even if we submit 100 tasks, they're going to be executed one by one in sequence only if there are multiple concurrently running tasks in your application that used the same resource, then the reads and writes on that resource need to be synchronized. However, if you use a single threat, execute ER to execute all those tasks. Then they need for synchronization is removed as it us execute sequentially now, and only one task will be accessing the common resource at a time. So using a single thread execute er can be a solution. Toe those cases where you need to synchronize our serialized access to a common resource. That's all I had on single thread Execute Er's. This was a short one. See you in the next section now by 10. Creating Threads Using Executors Framework - Cached Thread Pool | Part - 1: Hello, folks. In this video, we will see how to work with case threat pool execute er's as you already know from one of the previous videos, a case threat pool execute ER creates as many threads as required for executing the submitted tasks. If a task is submitted to it and a thread is available, then that thread is used to run the task. However, if all the threads are busy executing previously submitted tasks, then a new thread is created and the new task is executed by that thread. There is no concept off a task you here as soon as our task is submitted, it is immediately executed by this. Execute er When the threat has finished executing its task, it becomes available and is reused for the next task that is submitted. Toe this execute er just like the fixed threat pool. So the difference between a fixed threat pool execute er and a case threat pull execute er is that in a fixed thread pull execute er, the number of threads is fixed, while it is not so in the case threat pool. So if the number off submitted tasks exceeds the number off threads in the fixed Red Bull. Then the extra tasks have to wait in a task you till the time some thread finishes executing a previous task and becomes available to execute another task from the Cube. However, in a case threat, pull execute er there is no limit on the number off threads that can be created by the pool as many number off threads are created as a required in order to run all the submitted tasks concurrently so that no task has to wait for execution. That is why there is no concept off await you in case threat pool execute er as the usage off case threat pull execute er is similar to fix threat pool. So I'm just going to copy the using fixed thread pool class to make the using case thread pool class. I'm also going to keep the loop task a open in view for those students who have directly jumped toe this video and have not seen the previous ones so they can refer to loop task a class easily from the screen itself. Now the only difference between the usage off fixed threat pool execute er and the case threat pull execute er is the method you call on the executors class for case threat pool execute er we call the new case threat pool method and we still get an instance off execute er service when we call this method so we can use exactly the same code for this execute er as we had returned for fixed threat pool. This is the advantage off according to interface. But for the purpose off our exploration, let us just submit three tasks for the time being. Let us also not submit any task after the service has been shut down. We have already seen in the previous video that it will just throw a rejected execution exception. But I think it no. We see that all the three tasks have started to run concurrently and the output is similar to what we got in the previous tutorial. Let us know submit six tasks instead, off three and running again. We see that all the six tests have started running concurrently now. So from this exploration, we have observed that the case threat pool creates as many threads as the number of submitted tasks and runs all the submitted tasks at once. without making any task, wait in a queue. Now we have discussed previously that the threads in a case thread pool are reused if they're available when a new task is submitted in order to see the reuse, often existing thread we need to know how to name the threads first. Then we can print the names off threads to, in addition to the names off the tasks in the sea salt logs that will help us determine which task is running in which thread. And so if a thread is being reused, it will also become evident as we haven't covered how to name the threads yet. So we're going to do this exploration in another section where we examine the concepts off naming the threads. This brings us to the end of the current session. In the next session, we will discuss about the single thread execute Ear's see you there, build in peace to you and by