Java ExecutorService - Part 4 - Callable / Future

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
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
Info
Channel: Defog Tech
Views: 109,271
Rating: 4.9545622 out of 5
Keywords: Java, Java ExecutorService, Java ThreadPool
Id: NEZ2ASoP_nY
Channel Id: undefined
Length: 13min 7sec (787 seconds)
Published: Sat Jan 06 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.