Java ExecutorService – Part 1 – Introduction
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703087318_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Java ExecutorService – Part 1 – Introduction
In Java it’s always been easy to run a method or piece of code or synchronously that is if you have a main method which has a main thread you can run your tasks in a separate thread and you can do this very easily using a code similar to this
So you can create a class say for example tasks which implements honorable you can override its run method put the code that you want to run synchronously in this case we are just doing the system dot out dot println which will print the name of the thread that it is
Running in you can create a new thread and with the instance of this particular task and then just start the thread and the way to visualize this is there is a main thread which performs its operation from top to down at a certain point in
Time it will do thread dot start and the Java will create a thread named thread – 0 this thread will do its own operations and once those operations are done Java will kill that thread and the main thread will keep going to extend this if you want to similarly run ten tasks you
Can have the same class task which implements turnable but now you can create the threads in a for loop so in this for loop you have I equal to 0 to 10 so we runs ten times each time it will create a new thread with a new
Instance of task and will start that thread and the way to visualize this is very similar where Java will create threads called thread – 0 till thread – 9 denoted by T 0 to T 9 here and once the operations within the run method are complete Java will kill those threads to
Extend this even further what if you want to run 1000 tasks or synchronously the problem here is in Java 1 javathread corresponds to one operating system thread that means if you run the for loop thousand times it will create one thousand threads from p 0 to P nine nine nine
And creating a thread in itself is an expensive operation what you rather want is you want a fixed number of threads say 10 threads you want to create them upfront let’s call it a pool a pool of threads that’s why the name thread pool and let’s submit
Thousand tasks to them and then we want the threads to pick up those tasks complete tasks say for example t0 will pick one task call task 1 it will complete that task and then immediately start with task 2 similarly all the threads will pick up the tasks and
Execute them and the way to code this is very simple you create a new fixed thread pool using the static constructor or the static method of executors class here we are giving the number of threads as 10 will give back the instance variable for executor service and now
You use the same for loop that you used earlier but here instead of starting a new thread you can just submit or execute those tasks new tasks using the same service and the way to visualize this is that you have a for loop but within the for loop now instead of
Creating new threads you’re just creating new tasks and submitting them to the service and within the service which is the thread pool executors it internally uses a blocking queue in that queue it keeps storing all the tasks that you have submitted and all the 10
Threads which is T 0 to t 9 all of them will perform these same two steps the two steps are fetched the next task from the queue and execute it and since all 10 threads attempt to take the task from the queue at the same time that is
Concurrently you want the queue to be able to handle concurrent operations so you want a queue which is thread safe and that is why a third pool uses the blocking queue which is thread safe operation so what is the ideal pool size that you in this example we spoke about having 10
Threats and be submitted 1,000 jobs which is 1,000 tasks so the answer is not simple it depends on the type of tasks you want to exclude so let’s say you have CPU intensive operations so within the run method you have a particular snippet of code which takes a
Lot of CPU let’s say it’s an algorithm to create and hash or and cryptographic function in this case the task will take a lot of CPU and in Java as I said one javathread corresponds to one ôs thread right so if you have a CPU with four
Cores at a time you can have only four threads running so that means no matter how many threads you have here you can have 1000 threads but if your CPU itself can run only four cores at a time it will do a time splits scheduling so it
Will give some time to be 0 it will bump it off then it give it will give some time for t1 it will bump it off right so having too many threads is not a particularly good idea when you have CPU intensive operations so in that
Case the ideal pool size is to have the same number of threads as your number of cores in the cpu so in this case you have only four threads t0 t1 t2 and t3 so that means in a very ideal scenario you can have all 4 cores
Running these all four threads and none of the threads are waiting for anything and the code for this is very simple as well all you have to do apart from what we did already is to get the number of available processors varium program is running so in this case if you already
Have a method called run time to get run time not available processes that will give you the count of course that your cpu has and then you that particular count you can pass in when you are creating the thread pool and then you can do the same thing of
Submitting all the tasks to the service using its execute method but there are other kinds of tasks also suppose you have a task which is an i/o of intensive operation when I say IO intensive operation let’s say your task is to get some data from the database or your task
Calls an HTTP URL and gets the data from there here what happens is once those requests are made to the database or the HTTP client it will wait for the operating system to get a response and all those threads will go into a beating state so even though you have four cores
There is no point of having only few threads because all the threads are probably waiting for the operation to finish and there are no threads to fetch the nest next task and execute it so if your tasks are IO intensive which is database calls HTTP calls any network
Calls then in that case you can have the size of your pool as a large one so let’s assume the size of the pool is 100 so you have T 0 to T 99 so even if you have too many threads T 3 T 5 T 67 and
So on in the waiting state you can still have some other threads which are waiting and ready to fetch the task and execute it so once you have decided on the number of threads to use for your pool size you can write the code for this very similar to what we did earlier
Which is executors start new fix Ted pool and you pass in the number of the higher number that we have decided to be hundred and then the rest of the code remains as is which is have a for loop and do service not execute and pass in
Your i/o intensive task to it so to summarize if your task is a CPU intensive task then the ideal pool size is to have a CPU core count size that is the number of course available your CPU but there is a consideration to be made here if your CPU is also running
Multiple other applications your application might not get access to all the cores of the CPU so in that case even if you have kept the pool size as say four or if it’s a server CPU maybe the core size is 16 but if that server is running other applications your
Application will not get access to all those 16 cores right so there is a consideration to the weight similarly if your task is IO intensive you can have an higher pool size which will depend on the rate of the task submissions that is how fast you want to submit the new
Tasks and the average wait time for each task for the i/o operation to complete so it’s a trade-off you don’t want too many threads to be in the blocking state neither you want too many tasks to be waiting to be fetched by the threads right because remember if you have too
Many threads then it increases the memory consumption also that’s it for this video in the next videos we’ll take a look at the type of thread pools that Java provides and the life cycle methods for Java thread pools thanks for watching
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
explanation is good
🙂
if thread pool internally using blocking queue which is thread safe then how thread pool executing those task synchronously ?
Because if t0 picks up the task1 so t1 can't picks up task 2 until t0 doesn't finish its work, because blocking queue is thread safe so it will not release other thread until first doesn't finish ?
right ?
Thank You Deepak bhaiya for explaing this concept so beautifully
Thank you so much for the content
This executor service series is one of the best ever educational YouTube series ever. Thanks a ton. Your explanation is awesome.
All the concepts u given is aksed in an interview, best explanation ❤
thanks
Great explanation
Explained very well!!
Best explanation ever, thanks for it😇😇
Thank very much
Very well explained, thanks!
Well explained, thanku so much
Very informative!
Thanks for this clear explanation. You are doing a great job. I just wonder what is the strategy you follow to learn the concepts in crystal clear?
Could you also share the resources (book, articles, docs) you follow when you were learning this topics?
Amazing content.
Thanks a lot 😉
Clear and concise. As simple as it can get. Keep up the good work!
explaining with how , why , what , when ————– everything about the topic ——– hats off ———– u will complete 100k soon bro
Beautiful explanation
Great Explanation, 👍Could you please link this explanation to some Real-time scenarios(Enterprise applications)
Bestest explanation seen on Internet, thank you so much.
A Thread pool is a good concept to handle multiple tasks asynchronously. In case of more incoming tasks, we can hold them in the queue. How can we limit the incoming tasks held in the queue?
Awesome use of visualizations. This is really helpful, thank you!
You should post more bro.
You really explain complicated topics in a really simple manner.
Hi Deepak, I just watched all your 4 videos related to ExecutorService, you have shown how things can be explained in a super simple way yet powerful. Great job!! thanks.
A very nice tutorial. However, we missed to highlight one very important aspect and that is while using ExecutorService, one must call shutdown() when you are done calling all your tasks. And finally await with awaitTermination in a possible finally block. If we don't do that the ExecutorService continuous to listen for more tasks and doesnt kill itself automatically.
Thank you, is there any equation for determining thread pool size approximately? Right now it seems to be computed heuristically.
I as individual surf youtube a lot for learning purpose and almost have watched most of the youtuber on internet, But this channel is at another level in terms of quality . Thanks a lot sir . It would be great if you could take out some time and nail the microservice buzz words
Awesome explanation.. love your work brother
Really great explanation, adding one formula for I/O intensive task, according to "Java Concurrency in Practice"
Number of threads = Number of Available Cores * (1 + Wait time / Service time)
Explained very nicely 👌
Thank u so much sir
Can we have two thread pools, one for io tasks and another for cpu intensive tasks?
Defog come back and do more videos you are the best in explaining complex concepts buddy
Please help me this doubt
I have an API (Spring BOOT )which takes Employee ID
In its service layer I'm calling 3 different external API and for this i have used multithreading by creating 3 threads to do this task.
Now suppose my API is called concurrently by 100s of users how will the flow will
i.e One thread per request and then having 3 threads internally doing the process
OR One thread per request but bcoz of 3 threads in my service layer waiting for the thread to complete the task ?
Excellent Explanation 👍
THANK YOU !!! A LOT OF THANKS. There is no better explanation than yours. You are the best. Keep going
Defog Tech! You live upto your name
Holy Moli buddy!!! This was spot on! The BEST on the internet, cleared all my doubts right from basics to advance.. Super Thanks, I really appreciate great people like you that helps the community.
awesome explanation .. really like it
The best till now. Thanks.
Man .. god bless you!! Thanks!! you explain complex topics in a way anyone can understand.