I've got this exact question on an interview and answered confidently: ScheduledExecutorService or CompletableFuture. I binge watched your Java Concurrency playlist the day before. Thank you so much!!
truly great. Thread.stop() got depreciated cus it can mess the program, imagine some important task is running (writing a file) in the thread and suddenly Thread.stop() is called.
Great!! Thanks for the valuable content you provide. Understanding multithreading has not been easy always but your videos have proven to be real blessings!! Thanks a lot sir
For someone who is learning advanced java, your videos are one of the best resources I've found online. Appreciate your effort to put all these together. Can you recommend me some book(s) for mastering topics like concurrency, thread safety, writing multithreaded code, learning new java APIs, etc.?
Can I ask the maker of the video, where were you all these days? We missed your videos for a long period. Multithreading indeed is the very advance and necessary topic in Java. We would love to get more videos. Also if you can make videos on Design patterns, it will be great.
Sir, I try to make 1 video per week. I have been both busy and lazy lately :) I aim to make and upload much more frequently. Next 3-4 videos are all about java concurrency interviews. Hope they will be useful. Thank you so much for the support and love shown so far!! It helps me be motivated..
You are amazingly good man..keep the good work up. I also started recently videos for tech content and trying to be little less lazy and hope will share the url once it's enough as of now just started but your voice and clarification and design of content is awesome.
Its rather just easy to use awaitTermination for 10 mins on the the threadpool. It locks the main for 10 mins and as soon as it expires trigger the interrupts across all threads.
The theory is amazing yet simple. Best in TH-cam. 👍 👍 👍 Saved my life :) In my recent interviews for one of the leading investment banks , they asked me several practical coding question related to the topics you covered in this playlist. Can you please make a new video on solving such coding multi threading questions.Thanks in Advance.
Thank you for your clear and succinct explanations. Create a book with all these topics - one per chapter. I think it will sell very well. You can use the self-service LeanPub or other online publishers to create and publish your book.
10:23, is the task required to check on isInterrupted for this implementation to work ? Or can I simply rely on future.get Timeout to be sure that the task will be cancelled if the time out has exceeded?
Great content and explanation. A guide to Java Async programming. What in case of CompletableFuture orTimeout(long timeout, TimeUnit unit) ( or completeOnTimeout) Will the underlying thread gets canceled?
1. There is a stop method in Thread class, but it is deprecated long ago because it is unsafe for your data to stop like that and not because "threads are cooperative in nature" 2. if (booleanValue == true) --> if (booleanValue)
the way of explaining concepts in step by step manner using pictorial representations and at perfect pace is commendable. This helps to absorb things for eternity. You can move (What are Java interrupts?) to this playlist and Introduction to Completable future as well so that everything is avaialable under 1 umbrella. One question, just to confirm: so in web application, in case of IO operations, it may go into thread starvation as many threads at a time in server pool will be all engaged / can get busy. However, in case of non web applications, in case of IO operation, the moment thread goes to block state, context swithing will happen and thread will be offloaded from cpu so as to server another task / thread. Because many of your videos (be it async programming or webflux) revolve around point 1 eventhough second point is also correct as explained in Spinlock. Is this correct understanding?
Any thread which is waiting on IO does not occupy the CPU. It goes into waiting state and is offloaded from CPU. In case of web servers total thread count (say 200) limits number of simultaneous requests since even though CPU is free all 200 threads could be in waiting state. And threads are expensive (1-2 MB) so it's not wise to create too many of them.
Wait, I'm consufed: on 01:03 you were saying there's no API to stop a Thread, while on 09:26 you are calling "stop()" method of the Thread class. So, is there API to stop or not?
You are using while() loop & interrupt, but then you are assuming your code in run() method can come back to while() loop, but that does not always happen, right?
Me too have the same question. I feel that it is an invalid solution. Challenge for any thread to stop, is to abruptly leave the work/task whatever it was doing. It is not really an issue of stopping a iterative task after some iterations or just one iteration. May be shutdownhook helps?!
Hey, can you tell me how to implement a case where multiple threads want to acquire a lock on an object and only the first one is allowed to process it. remaining threads which are waiting can be removed so that they can work on something else instead of waiting.
The biggest confusion I have is how to then write the Task code in a way that we are able to check for interrupts between subsequent statements of evaluations. When we write a function, we write it imperatively, focussing on the logic that we want to implement. Putting a literal if or a global while between every statement is something I've never seen anybody coding
In 99% of the cases you will never want to check for interrupts. It is only useful when your tasks are very long and there are reasons due to which you may want to cancel that task mid-way.
@Defog - should the easiest solution be to join the thread with timeout set as 10 min ? t.join(10*60*1000); This will make main thread wait for 10 mins and interrupt the spun thread ? Kindly correct if I am wrong or misunderstood the requirement
As always like your all other videos short, clear and easy to understand. I'm a big fan of your channel now. Hoping to learn more with your videos. Keep continuing the good work man. 😊 May I please know which tool you use to showcase the PPT? Thanks.!!!
Great video but I don't understand one thing: if we include our steps in a while loop it will go through all steps and then check the condition and repeats this over. What if we want these steps to be different from one another and be executed only once. We cant just put them in while loop can't we?
Great video... If you use lock / unlock, how do you guarantee that the lock if acquired will be surly unlocked after say 3 seconds? This is because the caller of the class using lock/unlock may forget to unlock and in such case, we want to ensure it is going to be unlocked no matter what. How is that possible?
AFAIK there is no such API in Java. Its upto the developer to unlock, preferably in finally blocks. FWIW, if you forget to unlock, most likely you will catch that during testing itself since no other thread will be able to acquire the lock for duration of entire run.
It's deprecated, meaning you shouldn't use it. And anyone reviewing your code in either an interview or real life would hopefully not let you use it ;)
help me understand this, `while(keepRunning == true) { ...... }`. Once you're inside the while loop, and you have got multiple steps (say readBalance(), debitAmount(), notifySuccess()), how are you expecting that the execution will halt in between these steps and read the `keepRunning` value again, unless the loop re-iterates next time(after all the 3 steps). It will be like an infinite loop, won't it? Since, the while loop condition is checked at the `beginning of each iteration`, the loop will `continue to execute` the current iteration even after `keepRunning` becomes false. It will stop ONLLY at the beginning of the next iteration when the condition `(keepRunning == true)` is false. Correct me if I'm wrong here :) Thanks for the video!
Simplest way is to acquire the locks in same order in all threads, that would avoid locks. If locks are based on objects then get hashCode of object, sort based on that hashCode, then acquire locks in that order.
Avoid circular wait (i.e acquiring lock ) and to break circular wait you acquire locks in all threads in same sequence. T1 - lockA --> lockB T2 - lockA --> lockB
the way you explain this is really mind blowing. Just one question Executors.execute return the ExecutorService and Executors.submit return the Future Object, is this correct ?
It was removed purposely since if you stop the thread, the objects it was mutating can be in bad state.. since only that thread knows what should be the right state of the object, it should be allowed to change object state properly and only then stop
Need one help in one scenario. I am creating a new thread which does recursive task. After some time thread gives stack over flow error. I want to run recursive task with out giving stack overflow error. How to do it?
Issue is not thread related, it is about number of times the recursive task being called. Put a counter and see what the count is and when program stops printing it.
StackOverflow in a recursion occurs if your exit condition is not met in any of the iterations. Exit condition helps your stack to collapse back to initial state. Try creating Euler diagram for few iterations.
I guess essence of future.get(10) is that it will wait for 10 min max to get the result not that it would necessarily wait for 10 min. what we want for our solution is that there should be delay for 10 min before stopping the thread. so do u all think this soln is valid?
Hit like if you need more videos on interview questions. 👍
Kudos to the way the content is designed, displayed and articulately explained. Very useful for advanced developers.
instablaster
I've got this exact question on an interview and answered confidently: ScheduledExecutorService or CompletableFuture. I binge watched your Java Concurrency playlist the day before. Thank you so much!!
Thats so awesome to hear! Glad these videos helped
haven't found a better concurrency tutorial on youtube till date
Kudos
Honestly speaking i have never seen such an awesome explanation of this topic.
This video is a rare gem.
truly great. Thread.stop() got depreciated cus it can mess the program, imagine some important task is running (writing a file) in the thread and suddenly Thread.stop() is called.
Sound, Video, clarity.... all 100%
Your videos have really helped me understand Java's concurrency model. Cheers!
Please keep making such videos.. Really helpful!! 🙏🏻 Very well explained admin !! God bless you 😇
I regret that i have not seen ur videos for this long. u made hard concepts looks simple. Please do more videos if possible.
I dont think anybody can explain the java concurrency like you. Thankyou very much brother. Keep this up.
Thank you bro!
One word for videos is just BRILLIANT.....
Just one word- Marvelous explanation
Hats off to ur efforts and elegancy. You have earned a subscriber.
Dude..... the best explanation you can get it on youtube...Thank you so much.
This is so useful, keep up with the good work, man :) Cheers from Brazil!
You are certainly best of a lot when it comes to content and way of explaining. Keep it up! Git url with code would be great ! Thanks.
All your videos have been top quality. Please keep up the great work!
Great!! Thanks for the valuable content you provide. Understanding multithreading has not been easy always but your videos have proven to be real blessings!! Thanks a lot sir
Danke!
For someone who is learning advanced java, your videos are one of the best resources I've found online. Appreciate your effort to put all these together. Can you recommend me some book(s) for mastering topics like concurrency, thread safety, writing multithreaded code, learning new java APIs, etc.?
Concurrency in practice is a good book.. other than that personally haven't liked any..
Explained in a very very simplified way. Superb!
Wow. So crisp n clear
You explain so good . 😊
Thank you for your videos 🙏🏻❤️
Best explanation..... Please post more of these 🙏
Thanks sir sooo beautiful explanation ❣️
Can I ask the maker of the video, where were you all these days? We missed your videos for a long period. Multithreading indeed is the very advance and necessary topic in Java. We would love to get more videos. Also if you can make videos on Design patterns, it will be great.
Sir, I try to make 1 video per week. I have been both busy and lazy lately :) I aim to make and upload much more frequently.
Next 3-4 videos are all about java concurrency interviews. Hope they will be useful.
Thank you so much for the support and love shown so far!! It helps me be motivated..
You are amazingly good man..keep the good work up. I also started recently videos for tech content and trying to be little less lazy and hope will share the url once it's enough as of now just started but your voice and clarification and design of content is awesome.
You are awesome. Your channel deserves more subscribers
Thank you for your kind words sir!
Upvote + 10 points for pointing a note on IO Operations case!
Its rather just easy to use awaitTermination for 10 mins on the the threadpool. It locks the main for 10 mins and as soon as it expires trigger the interrupts across all threads.
Thanks bro! Keep making , no one can explain better than you. Cheers!!
Awesome explanation..Hats off to you..
Ur really doing great job,
God bless you.
Real interview question for me and failed miserably. Thanks for the video.
The theory is amazing yet simple. Best in TH-cam. 👍 👍 👍 Saved my life :)
In my recent interviews for one of the leading investment banks , they asked me several practical coding question related to the topics you covered in this playlist. Can you please make a new video on solving such coding multi threading questions.Thanks in Advance.
Very perspicuous and transparent ! Thank you 👍
Hi, your explanations are out of this world. Could you please make a video on thread-safety in static methods, please?
Very organized content, Please keep creating videos
Really amazing content. Hoping to see more.
Great video! Suggestion for another video which is also an interview question "Implement a delayed scheduler"
Thank you! That's a good idea
Love this channel
Great tutorial, Dude
Thanks for content. 👍.
More such interview questions, please. Thanks
good stuff... really liked and explained very well...
Thank you for your clear and succinct explanations.
Create a book with all these topics - one per chapter. I think it will sell very well. You can use the self-service LeanPub or other online publishers to create and publish your book.
Great suggestion! Let me think about it
Perfectly explained!
10:23, is the task required to check on isInterrupted for this implementation to work ? Or can I simply rely on future.get Timeout to be sure that the task will be cancelled if the time out has exceeded?
Very well done presentation! Kudos
very helpful tutorial
Plz explain saga design pattern in microservice .Practical implementation will be much more appreciated.
bro why you have stopped making videos. Please make videos on Java/Rx Java. you are awesome !!
Good stuff. You dont need the keepRunning to public if you use the stop()
Thread class does have method called stop() that can immediately stops execution of a task, but deprecated as it is inherently unsafe
It will start throwing exception now - bugs.openjdk.org/browse/JDK-8289610
Great content and explanation. A guide to Java Async programming.
What in case of CompletableFuture orTimeout(long timeout, TimeUnit unit) ( or completeOnTimeout)
Will the underlying thread gets canceled?
awesome man... keep going
1. There is a stop method in Thread class, but it is deprecated long ago because it is unsafe for your data to stop like that and not because "threads are cooperative in nature"
2. if (booleanValue == true) --> if (booleanValue)
Good Explanation! Can you make video of "Hanging Thread Detection and Handling
"
Sir will you make a vedio on Netty server how it internally works please no good source is available in internet
the way of explaining concepts in step by step manner using pictorial representations and at perfect pace is commendable. This helps to absorb things for eternity.
You can move (What are Java interrupts?) to this playlist and Introduction to Completable future as well so that everything is avaialable under 1 umbrella.
One question, just to confirm:
so in web application, in case of IO operations, it may go into thread starvation as many threads at a time in server pool will be all engaged / can get busy.
However, in case of non web applications, in case of IO operation, the moment thread goes to block state, context swithing will happen and thread will be offloaded from cpu so as to server another task / thread.
Because many of your videos (be it async programming or webflux) revolve around point 1 eventhough second point is also correct as explained in Spinlock.
Is this correct understanding?
Any thread which is waiting on IO does not occupy the CPU. It goes into waiting state and is offloaded from CPU. In case of web servers total thread count (say 200) limits number of simultaneous requests since even though CPU is free all 200 threads could be in waiting state.
And threads are expensive (1-2 MB) so it's not wise to create too many of them.
@@DefogTech thanks for quick reply. How to check thread size in MBs? Also of any datastructure?
excellent........you are awesome.
Wait, I'm consufed:
on 01:03 you were saying there's no API to stop a Thread,
while on 09:26 you are calling "stop()" method of the Thread class.
So, is there API to stop or not?
Great Work thank you so much
Thanks for your video, how can we achieve same with threads running across various jvm?
You are using while() loop & interrupt, but then you are assuming your code in run() method can come back to while() loop, but that does not always happen, right?
Me too have the same question. I feel that it is an invalid solution. Challenge for any thread to stop, is to abruptly leave the work/task whatever it was doing. It is not really an issue of stopping a iterative task after some iterations or just one iteration. May be shutdownhook helps?!
Hey, can you tell me how to implement a case where multiple threads want to acquire a lock on an object and only the first one is allowed to process it. remaining threads which are waiting can be removed so that they can work on something else instead of waiting.
Great video.
Very knowledgeable
excellent explanation thanks.
Super explained
bro.. could you do a video on Big 0 notation?
Can you please explain why while timeout we are using stop() method when this method is not supported anymore.
Super!
The biggest confusion I have is how to then write the Task code in a way that we are able to check for interrupts between subsequent statements of evaluations. When we write a function, we write it imperatively, focussing on the logic that we want to implement. Putting a literal if or a global while between every statement is something I've never seen anybody coding
In 99% of the cases you will never want to check for interrupts. It is only useful when your tasks are very long and there are reasons due to which you may want to cancel that task mid-way.
@Defog - should the easiest solution be to join the thread with timeout set as 10 min ?
t.join(10*60*1000);
This will make main thread wait for 10 mins and interrupt the spun thread ? Kindly correct if I am wrong or misunderstood the requirement
As always like your all other videos short, clear and easy to understand. I'm a big fan of your channel now. Hoping to learn more with your videos. Keep continuing the good work man. 😊 May I please know which tool you use to showcase the PPT? Thanks.!!!
Thanks buddy! I use Google Slides for presentation
Great video but I don't understand one thing: if we include our steps in a while loop it will go through all steps and then check the condition and repeats this over. What if we want these steps to be different from one another and be executed only once. We cant just put them in while loop can't we?
correct, in that case before every step we will need to add this if condition checking for volatile or interrupt..
I had the same question.
Nice explanation
Make more videos like this!
thank you for this video very good !!!
@Defog Tech : Please create videos on java collections.
Great video...
If you use lock / unlock, how do you guarantee that the lock if acquired will be surly unlocked after say 3 seconds? This is because the caller of the class using lock/unlock may forget to unlock and in such case, we want to ensure it is going to be unlocked no matter what. How is that possible?
AFAIK there is no such API in Java. Its upto the developer to unlock, preferably in finally blocks. FWIW, if you forget to unlock, most likely you will catch that during testing itself since no other thread will be able to acquire the lock for duration of entire run.
Amazing
1:05 you said there is not stop() method to stop the thread. But as far as I know, there is indeed a stop() but just deprecated.
It's deprecated, meaning you shouldn't use it. And anyone reviewing your code in either an interview or real life would hopefully not let you use it ;)
Which logic will be there in task.stop() ?
Thank you so much!
help me understand this, `while(keepRunning == true) { ...... }`. Once you're inside the while loop, and you have got multiple steps (say readBalance(), debitAmount(), notifySuccess()), how are you expecting that the execution will halt in between these steps and read the `keepRunning` value again, unless the loop re-iterates next time(after all the 3 steps). It will be like an infinite loop, won't it? Since, the while loop condition is checked at the `beginning of each iteration`, the loop will `continue to execute` the current iteration even after `keepRunning` becomes false.
It will stop ONLLY at the beginning of the next iteration when the condition `(keepRunning == true)` is false. Correct me if I'm wrong here :) Thanks for the video!
@Defog, how to handle deadlock situation and how to resolve it?
Simplest way is to acquire the locks in same order in all threads, that would avoid locks. If locks are based on objects then get hashCode of object, sort based on that hashCode, then acquire locks in that order.
Avoid circular wait (i.e acquiring lock ) and to break circular wait you acquire locks in all threads in same sequence.
T1 - lockA --> lockB
T2 - lockA --> lockB
how can i create a runtime class and mapped it with hibernate without adding and restarting our application please make a video on it.
Please share more interview questions
the way you explain this is really mind blowing. Just one question Executors.execute return the ExecutorService and Executors.submit return the Future Object, is this correct ?
Execute method returns void, submit will return future but for callable only... Not 100 percent sure, can you please check the docs
What happens when your task calls a library that swallows the InterruptedException (I've seen this in certain JDBC drivers)? .
That's IO operation, most java IO librarues respect the interrupts but yes, it's upto the library code to handle it.
there is stop() in Thread class but its deprecated, but that would be a very simple solution.
It was removed purposely since if you stop the thread, the objects it was mutating can be in bad state.. since only that thread knows what should be the right state of the object, it should be allowed to change object state properly and only then stop
Need one help in one scenario. I am creating a new thread which does recursive task. After some time thread gives stack over flow error. I want to run recursive task with out giving stack overflow error. How to do it?
Issue is not thread related, it is about number of times the recursive task being called. Put a counter and see what the count is and when program stops printing it.
StackOverflow in a recursion occurs if your exit condition is not met in any of the iterations. Exit condition helps your stack to collapse back to initial state. Try creating Euler diagram for few iterations.
Can you make a video on Static and non-static synchronization, I have been asked this question many times and recruiter never seems to be happy.
Can you elaborate more on the question?
can you please share these slides?
So, does it mean that we can never guarantee to stop/cancel a thread at a given point of time? Please correct if I have got it all wrong
yes, thats correct..
Is there any way to timeout the HttpRequest after a specified time ? I tried both Connection_Timeout and Read_Timeout ? thanks
Yes, I haven't used core API for Http connection but libraries like Retrofit and Spring http client both allow you to set timeouts
I guess essence of future.get(10) is that it will wait for 10 min max to get the result not that it would necessarily wait for 10 min.
what we want for our solution is that there should be delay for 10 min before stopping the thread. so do u all think this soln is valid?