Java ExecutorService – Part 4 – Callable / Future
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703217534_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: Java ExecutorService – Part 4 – Callable / Future
In the previous videos for the executor service we saw how to submit the tasks which is nothing but a class which implements runnable wherein you can define the number of steps to execute in a separate thread within the run method and how to submit those tasks using the
Execute method but there is a distinct use case that we did not see we did not see what if the task is implemented such that it wants to return a value so suppose I want to return a value from this run method there is no way I can do
That say I want to return a value of 3 all the time I cannot do that because the round herbal interface to go inside the runnable interface you will see there is only a single method called run and the return type of that run method
Is void so there is no way you can return a value go back so there is another class called callable which is created exactly for this purpose so instead of runnable if we implement a callable interface which is this and you mentioned it is generic space so you
Mentioned which kind of variable you are going to return so let’s say here we are going to return an integer right now IntelliJ is telling me to implement the method and let’s delete this run method first now callable interface has this method called call and based on what genrich’s
You mentioned here it will return that particular value now we can very easily return a particular value now let’s say instead of always returning 3 let me do something fancy by saying return always return a random number okay but now if you see there is a compile time
Exception during the submission of the task right now let’s first just delete this for loop we don’t want to do this 100 times let’s say we want to do it only once for now it is compiled MX is because the execute method expects a runnable task but instead now we have a
Callable task and there is a separate method in the executor service to submit the call by tasks and the method name is submit and as you can see you can submit even a runnable task which works the same way as triggering the execute so there is no difference there but if you
Want to submit a callable tasks then you always have to use the submit so now there is no compile time exception we have submitted the task now we have to accept the value of this method call this integer value here which is being returned we have to accept it in some
Variable so let’s say that label is future the future type should have been integer but it is not it is of a type of class called future as a name suggests it’s a placeholder for the value which will arrive sometime in the future and based on how long your call operation
Takes so let’s say your call operation here is let’s say thread dot sleep I want to emulate that this operation takes a long time so if we want to sleep for 3 seconds here and after that calculator on I can calculate the next random number now here for those 3
Seconds you can perform some other operations like you can say perform some operations I don’t know what but by the time the execute service is running your callable method in a separate thread you can perform some other operations some unrelated operations here right and then once those unrelated to operations are
Finished it may take 1 second 2 seconds 3 seconds whatever after those operations are finished you can say future not get ok and this will give you the actual integer result of that callable task now if these operations finish very fast let’s say these operations finish within one second
Right at this point in time your future is not ready with the value your your task sleeping for three seconds so by the time you do or dot get operation this method call is not finished and that is why this get operation is a blocking operation this particular call
Your main thread will block at this call until the future is ready to return a particular value right and the compile time exception is just because you have not surrounded it with try-catch so let’s do that so instead of doing a try/catch I’ve just added a throws execution exception in the main if
You’re not a fan of that you can surround it click try catch so again to reiterate future is nothing but a placeholder for the value which will arrive sometime in the future and how much time you can never be sure it will be completely based on how much time
Your call method takes you can also extend this particular submission for multiple tasks so like we did earlier we can have a for loop let’s say we want to submit hundred tasks so I’ll say for I equal to 0 to less than 100 and we can
Submit all those tasks and you will get 100 futures in return to store the hundred futures you can just use an adder list see here I’ll say future list I’ll say all futures equal to new analysts and as soon as I get a future during each submission I’ll store them
In this list right so at this point at this particular point you have 100 futures with 100 placeholders right none of them have actual values but you have 100 placeholders which will give you 100 values sometime in the future now you can do a lot of Papa unrelated
Operations here by the time the executor service is executing and completing all those hundred tasks it is perfectly possible by the time you come here say after 100 seconds some of the future tasks are completed and some of them are not completed here again if I use a for-loop
And I use the same method or the same snippet of code which will say future is equal to futures all futures don’t get I and I’ll get the value of that future just made a tiny mistake here it needs to be future of an integer now you do
Not have the compile time exception once you get a result you can say result of future number plus I is equal to and you get the value right so the whole point of having call bills in combination with futures is to submit the tasks which return some value do some unrelated
Operations while those tasks are being executed and after some point in time get those values from all the futures we can visualize all this in this matter so let’s say we have this service and we submitted a new task and that task is a callable task we get a value of variable
Of type future that future is nothing but a placeholder which is immediately returned by this thread pool so the rest of the thread pool works as is but immediately when you submit the task the thread pool gives you a placeholder to keep the placeholder this box is empty
There is no value within it after some point in time which is completely dependent on how your call method is implemented once the result is ready with the thread pool it will update the same placeholder which it gave you with the actual value now when this colorful method is being run if your
Main method calls the F dot gate method which is a blocking method which is shown here the main thread will immediately go into the block state because at this point in time the thread pool is not yet completed the call method and it is not ready with the
Result yet and that is why the main thread will go into the block state and once the thread pool sets the value of that placeholder that is when the call is completed then the main thread which was blocked again goes into the runnable state and then can be run subsequently
By the JVM and for this very reason you need to be extra careful when you are doing this using a for loop so suppose you have a for loop where you are submitting all these tasks multiple times to the executor service so let’s say in this case we are submitting four
Tasks of call ‘evil nature in this case even though the third and the fourth tasks are completed so in this case the placeholder already has the values for task number three and task number four and yet if you do an F dot get on the first placeholder the main thread will
Go into the block state because that particular placeholder is not yet complete and once you have that value in that particular place order then again the main thread will start running and the same problem will occur even for the second task which is still not completed
So again the main thread will go into the block state and it will wait until the second task is completed and the for the third and the fourth task it will never go into the block state because the futures already have the values so that’s one scenario where you have to be
Extra careful when using for loop for the list of futures one way to get around these problems is to use a timeout method so get method provides an overloaded method where you can submit the maximum amount of time that you are willing to wait for the task to come
So in this case I can say future get rate for a maximum amount of one second and within that time if the future is not ready with its value then just throw or timeout exception and since it’s a timeout exception which is a checked exception you have a catch method where
You can do the login or any other code you would do for the field result there are couple of other methods which can be useful and one is the cancel method so you can specifically say I no longer want to have this task executed so please stands cancel this task itself
There is one problem with this so if you say cancel before the thread pool has started working on it then it is well and good then the thread pool will immediately cancel it and will never run the task but if your task has already started running in one of the threads
Then this cancel will have no effect then you have to depend on the interrupts ability of that particular thread and that is why this method takes a boolean value of true or false if it’s true then that thread is attempted to be interrupted and interrupts in Java is a completely different ballgame which
We’ll talk about in a separate set of videos and you can also check the current status of that future using is canceled and instant methods and as the name suggests is cancelled it returns true if the task is canceled and is done returns true if the task is completed
Note that this returns true even if the task was completed as a failure if even there was an exception the task is of course never run again and that is why it returns it true so that’s it for now for these videos thanks a lot for listening if you have any requests of
What aspects of Java you want to learn then please let me know in the comments below and I will try to create videos for that
-
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
Great concent sir glad I found this channel
I have one question when should we call the shutdown method.
In the Predestroy state of the context ?
Great videos!
Do you have video for streams?
superb Explanation
Best video of callable interface
Please let me know if you have created any video for Completable future
You earned a subscriber my friend.
your explanation is far better than any udemy course…….. 🙂
Exceptional Wonderful. Thank you.
Exactly what was required
Could you kindly provide the Github link for your examples and slides, as it would be an excellent resource for everyone to learn from?
amazing teacher / guru. Thanks Defog Tech.
I have watched so many tutorials on executor service none of them can match this explanation, thanks a lot
Great, thanx
I tried same code, but not working
Excellent videos on executorService, understood every part of it. Thanks a lot 🙂
This is amazing tutorial. Thank you so much!!
man, your concurrency series is absolutely amazing!
謝謝!
Great job buddy!! 👍
This Helped a lot
The best explanation ever! Thank you. Better than java concurrency in practice
You are awesome bro. Thanks for your hard work you put in for this content 🙂
Very helpful and easy to understand video, thank you 🙂
Very good series on executors ! I didn't find any other better videos for this topic. Thank you!
Thumbs up for the amazing content…
The runnable and callable use core threads or virtual threads. Do one have a way to choose the type of threads ?
Great video….thanks a lot