Java Concurrency Interview Question: How to timeout a thread?

  Рет қаралды 125,963

Defog Tech

Defog Tech

Күн бұрын

Пікірлер: 146
@abhijitsalvi4170
@abhijitsalvi4170 5 жыл бұрын
Kudos to the way the content is designed, displayed and articulately explained. Very useful for advanced developers.
@richardashton5158
@richardashton5158 3 жыл бұрын
instablaster
@sharanyarai378
@sharanyarai378 5 жыл бұрын
Hit like if you need more videos on interview questions. 👍
@propertydelver
@propertydelver Жыл бұрын
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!!
@DefogTech
@DefogTech Жыл бұрын
Thats so awesome to hear! Glad these videos helped
@rohitsharma-xt8qe
@rohitsharma-xt8qe 5 жыл бұрын
Honestly speaking i have never seen such an awesome explanation of this topic.
@mohammedthahajk7619
@mohammedthahajk7619 3 жыл бұрын
haven't found a better concurrency tutorial on youtube till date Kudos
@giveaway4002
@giveaway4002 3 жыл бұрын
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.
@gosnooky
@gosnooky 5 жыл бұрын
Your videos have really helped me understand Java's concurrency model. Cheers!
@sushmithashenoy7581
@sushmithashenoy7581 2 ай бұрын
Hats off to ur efforts and elegancy. You have earned a subscriber.
@Dawntech
@Dawntech 5 жыл бұрын
This is so useful, keep up with the good work, man :) Cheers from Brazil!
@amanokuba4688
@amanokuba4688 5 жыл бұрын
Sound, Video, clarity.... all 100%
@ArjunKumar-zu2kl
@ArjunKumar-zu2kl 4 жыл бұрын
One word for videos is just BRILLIANT.....
@pavnn2347
@pavnn2347 4 жыл бұрын
I regret that i have not seen ur videos for this long. u made hard concepts looks simple. Please do more videos if possible.
@rohitjain1447
@rohitjain1447 5 жыл бұрын
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.
@DefogTech
@DefogTech 5 жыл бұрын
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..
@anoop1341
@anoop1341 5 жыл бұрын
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.
@deepmingle
@deepmingle 4 жыл бұрын
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.
@analogylibrary
@analogylibrary 5 жыл бұрын
Just one word- Marvelous explanation
@visalrao4733
@visalrao4733 4 жыл бұрын
Dude..... the best explanation you can get it on youtube...Thank you so much.
@GajendraSingh1990
@GajendraSingh1990 5 жыл бұрын
I dont think anybody can explain the java concurrency like you. Thankyou very much brother. Keep this up.
@DefogTech
@DefogTech 5 жыл бұрын
Thank you bro!
@drakezen
@drakezen 5 жыл бұрын
All your videos have been top quality. Please keep up the great work!
@ravicrazyster
@ravicrazyster 2 жыл бұрын
Wow. So crisp n clear
@tusharkarkera8615
@tusharkarkera8615 5 жыл бұрын
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.?
@DefogTech
@DefogTech 5 жыл бұрын
Concurrency in practice is a good book.. other than that personally haven't liked any..
@manognajoshik8465
@manognajoshik8465 2 жыл бұрын
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
@AmandeepSingh-sx9ke
@AmandeepSingh-sx9ke 5 жыл бұрын
You explain so good . 😊 Thank you for your videos 🙏🏻❤️
@dhananajaykrishna8259
@dhananajaykrishna8259 4 жыл бұрын
Best explanation..... Please post more of these 🙏
@nagarajubommarapu1523
@nagarajubommarapu1523 4 жыл бұрын
Explained in a very very simplified way. Superb!
@13success66
@13success66 2 жыл бұрын
Thanks sir sooo beautiful explanation ❣️
@harshadakhandekar4607
@harshadakhandekar4607 4 жыл бұрын
The theory is amazing yet simple. Best in KZbin. 👍 👍 👍 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.
@rajeevkandpal1880
@rajeevkandpal1880 2 ай бұрын
bro why you have stopped making videos. Please make videos on Java/Rx Java. you are awesome !!
@anjalikumari2796
@anjalikumari2796 3 жыл бұрын
Awesome explanation..Hats off to you..
@deepakmarneni2110
@deepakmarneni2110 5 жыл бұрын
You are awesome. Your channel deserves more subscribers
@DefogTech
@DefogTech 5 жыл бұрын
Thank you for your kind words sir!
@apoorvanayak1736
@apoorvanayak1736 2 жыл бұрын
Great video! Suggestion for another video which is also an interview question "Implement a delayed scheduler"
@DefogTech
@DefogTech 2 жыл бұрын
Thank you! That's a good idea
@ahadporkar7355
@ahadporkar7355 5 жыл бұрын
Very perspicuous and transparent ! Thank you 👍
@rohitjain1447
@rohitjain1447 5 жыл бұрын
Thanks bro! Keep making , no one can explain better than you. Cheers!!
@rishinjiya42
@rishinjiya42 4 жыл бұрын
Hi, your explanations are out of this world. Could you please make a video on thread-safety in static methods, please?
@ibrahimshaikh3642
@ibrahimshaikh3642 5 жыл бұрын
Ur really doing great job, God bless you.
@balak2811
@balak2811 4 жыл бұрын
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.
@venkateshrajendran2362
@venkateshrajendran2362 3 жыл бұрын
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?
@abhishekjm8611
@abhishekjm8611 4 жыл бұрын
Really amazing content. Hoping to see more.
@vijaykumarreddyt3287
@vijaykumarreddyt3287 Жыл бұрын
Great tutorial, Dude
@deepgsingh
@deepgsingh 5 жыл бұрын
Very organized content, Please keep creating videos
@justACatOnYoutube
@justACatOnYoutube 4 жыл бұрын
Upvote + 10 points for pointing a note on IO Operations case!
@mingli9563
@mingli9563 4 жыл бұрын
Love this channel
@MrAanjaneya
@MrAanjaneya 5 жыл бұрын
Real interview question for me and failed miserably. Thanks for the video.
@krishnapanigrahi6926
@krishnapanigrahi6926 3 жыл бұрын
Plz explain saga design pattern in microservice .Practical implementation will be much more appreciated.
@qataracgnacgn
@qataracgnacgn 2 жыл бұрын
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.
@DefogTech
@DefogTech 2 жыл бұрын
Great suggestion! Let me think about it
@tanveerengg
@tanveerengg 5 жыл бұрын
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?
@DefogTech
@DefogTech 5 жыл бұрын
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.
@tanveerengg
@tanveerengg 5 жыл бұрын
@@DefogTech thanks for quick reply. How to check thread size in MBs? Also of any datastructure?
@Nithin_Coorg
@Nithin_Coorg 5 жыл бұрын
Good Explanation! Can you make video of "Hanging Thread Detection and Handling "
@LakshmananMe
@LakshmananMe 5 жыл бұрын
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.!!!
@DefogTech
@DefogTech 5 жыл бұрын
Thanks buddy! I use Google Slides for presentation
@ayanSaha13291
@ayanSaha13291 2 жыл бұрын
Thanks for content. 👍.
@ianwanjala8621
@ianwanjala8621 3 ай бұрын
very helpful tutorial
@MilanKamboya
@MilanKamboya 5 жыл бұрын
good stuff... really liked and explained very well...
@amritabasu2243
@amritabasu2243 3 жыл бұрын
Good stuff. You dont need the keepRunning to public if you use the stop()
@vaib5917
@vaib5917 5 жыл бұрын
More such interview questions, please. Thanks
@ChrisAthanas
@ChrisAthanas 5 жыл бұрын
Very well done presentation! Kudos
@ILyaCyclone
@ILyaCyclone 5 жыл бұрын
Perfectly explained!
@TarekFaham
@TarekFaham 2 жыл бұрын
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?
@DefogTech
@DefogTech 2 жыл бұрын
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.
@MakeItStik
@MakeItStik 2 жыл бұрын
@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
@krrsss
@krrsss 5 жыл бұрын
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?
@DefogTech
@DefogTech 5 жыл бұрын
correct, in that case before every step we will need to add this if condition checking for volatile or interrupt..
@AmitGadaley17
@AmitGadaley17 3 жыл бұрын
I had the same question.
@windowcrystal4012
@windowcrystal4012 5 жыл бұрын
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?
@askalaveeska
@askalaveeska 4 жыл бұрын
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?!
@traptiagrawal1214
@traptiagrawal1214 4 жыл бұрын
Thanks for your video, how can we achieve same with threads running across various jvm?
@developerabhishek7099
@developerabhishek7099 3 жыл бұрын
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.
@mahendharkhedhar7887
@mahendharkhedhar7887 5 жыл бұрын
Sir will you make a vedio on Netty server how it internally works please no good source is available in internet
@Lucky-uz3je
@Lucky-uz3je 5 жыл бұрын
excellent........you are awesome.
@prashantsharma9856
@prashantsharma9856 5 жыл бұрын
Great Work thank you so much
@LivenLove
@LivenLove 5 жыл бұрын
excellent explanation thanks.
@alsto8298
@alsto8298 4 жыл бұрын
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)
@asankasiriwardena3383
@asankasiriwardena3383 2 жыл бұрын
Thread class does have method called stop() that can immediately stops execution of a task, but deprecated as it is inherently unsafe
@DefogTech
@DefogTech Жыл бұрын
It will start throwing exception now - bugs.openjdk.org/browse/JDK-8289610
@AbhishekVaid
@AbhishekVaid 2 жыл бұрын
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
@DefogTech
@DefogTech 2 жыл бұрын
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.
@satyanarayanajammala5129
@satyanarayanajammala5129 5 жыл бұрын
awesome man... keep going
@chandramoulisharma4188
@chandramoulisharma4188 5 жыл бұрын
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 ?
@DefogTech
@DefogTech 5 жыл бұрын
Execute method returns void, submit will return future but for callable only... Not 100 percent sure, can you please check the docs
@kumarashutosh229
@kumarashutosh229 4 ай бұрын
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!
@diegoramos27
@diegoramos27 5 жыл бұрын
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?
@youngsambyun5854
@youngsambyun5854 5 жыл бұрын
thank you for this video very good !!!
@ratneshchouhan6
@ratneshchouhan6 2 жыл бұрын
@Defog, how to handle deadlock situation and how to resolve it?
@DefogTech
@DefogTech 2 жыл бұрын
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.
@MakeItStik
@MakeItStik 2 жыл бұрын
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
@aakash24041990
@aakash24041990 4 жыл бұрын
@Defog Tech : Please create videos on java collections.
@kengerfil
@kengerfil 13 күн бұрын
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?
@ramanapanku4306
@ramanapanku4306 5 жыл бұрын
Very knowledgeable
@ashitateotia8101
@ashitateotia8101 3 жыл бұрын
Can you please explain why while timeout we are using stop() method when this method is not supported anymore.
@logicbuffer2162
@logicbuffer2162 5 жыл бұрын
Great video.
@dnbhatia85
@dnbhatia85 5 жыл бұрын
Super explained
@gopikumar857
@gopikumar857 Жыл бұрын
bro.. could you do a video on Big 0 notation?
@aleksandarvanced5434
@aleksandarvanced5434 5 жыл бұрын
Make more videos like this!
@shivendratiwari3238
@shivendratiwari3238 4 жыл бұрын
Bro why don't you create a playlist which dives deep in stream exploring all the APIs
@zss123456789
@zss123456789 4 жыл бұрын
Thank you so much!
@chandra111443
@chandra111443 5 жыл бұрын
Nice explanation
@shalingupta8281
@shalingupta8281 4 жыл бұрын
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.
@DefogTech
@DefogTech 4 жыл бұрын
Can you elaborate more on the question?
@nikkisingh1041
@nikkisingh1041 4 жыл бұрын
how can i create a runtime class and mapped it with hibernate without adding and restarting our application please make a video on it.
@prathameshchaudhari1306
@prathameshchaudhari1306 3 жыл бұрын
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?
@DefogTech
@DefogTech 3 жыл бұрын
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.
@MakeItStik
@MakeItStik 2 жыл бұрын
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.
@bigheat86
@bigheat86 3 жыл бұрын
Danke!
@SurendraBabuK
@SurendraBabuK 5 жыл бұрын
Which logic will be there in task.stop() ?
@slr150
@slr150 4 жыл бұрын
What happens when your task calls a library that swallows the InterruptedException (I've seen this in certain JDBC drivers)? .
@DefogTech
@DefogTech 4 жыл бұрын
That's IO operation, most java IO librarues respect the interrupts but yes, it's upto the library code to handle it.
@081sidd
@081sidd 5 жыл бұрын
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
@DefogTech
@DefogTech 5 жыл бұрын
yes, thats correct..
@windowcrystal4012
@windowcrystal4012 5 жыл бұрын
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.
@NathanJohnson815
@NathanJohnson815 5 жыл бұрын
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 ;)
@babasahebgongale5006
@babasahebgongale5006 3 жыл бұрын
Super!
@aurojitbasak3249
@aurojitbasak3249 5 жыл бұрын
Please share more interview questions
@maverick_entertainment21
@maverick_entertainment21 4 жыл бұрын
Amazing
@ironhide9955
@ironhide9955 5 жыл бұрын
there is stop() in Thread class but its deprecated, but that would be a very simple solution.
@DefogTech
@DefogTech 5 жыл бұрын
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
@chetanbhandari3033
@chetanbhandari3033 2 жыл бұрын
Bro thnx lot
@Existentialkev
@Existentialkev 5 жыл бұрын
Why would you use thread.sleep() for time out logic?? that would suspend the execution of the thread right? What the question wants is for you to ask the thread to stop *after* 10 minutes has elapsed which you demonstrated with the ExecutorService and Future.
@DefogTech
@DefogTech 5 жыл бұрын
Right, sleep() will suspend execution of current thread but the Runnable/task being executed in new thread or ExecutorService will continue to run
@Existentialkev
@Existentialkev 5 жыл бұрын
@@DefogTech I see so the idea is for the suspended thread to check the result of another thread that is actually doing the task in the runnable after a set amount of time? And if the task isn't complete call interrupt () ?
@DefogTech
@DefogTech 5 жыл бұрын
Exactly! Also yours is also a good point.. a simpler way could be for the task itself to note start time and every once in a while check if it's over deadline.. if so just return...
@diegoramos27
@diegoramos27 5 жыл бұрын
Is there any way to timeout the HttpRequest after a specified time ? I tried both Connection_Timeout and Read_Timeout ? thanks
@DefogTech
@DefogTech 5 жыл бұрын
Yes, I haven't used core API for Http connection but libraries like Retrofit and Spring http client both allow you to set timeouts
@shankarm2848
@shankarm2848 3 жыл бұрын
Is there any way to kill a interrupted thread without using while loop?
@DefogTech
@DefogTech 3 жыл бұрын
nope, threads are cooperative in Java, cant kill them.
Introduction to CompletableFuture in Java 8
19:34
Defog Tech
Рет қаралды 327 М.
🕊️Valera🕊️
00:34
DO$HIK
Рет қаралды 15 МЛН
HELP!!!
00:46
Natan por Aí
Рет қаралды 3,6 МЛН
Yay, My Dad Is a Vending Machine! 🛍️😆 #funny #prank #comedy
00:17
Python Decorators in 15 Minutes
15:14
Kite
Рет қаралды 447 М.
ThreadLocal in Java
10:59
Defog Tech
Рет қаралды 186 М.
Java Memory Model in 10 minutes
10:55
Defog Tech
Рет қаралды 262 М.
What is Spring Webflux and when to use it?
17:46
Defog Tech
Рет қаралды 244 М.
Understanding how ForkJoinPool works
13:16
Defog Tech
Рет қаралды 123 М.
Multithreading in Java Explained in 10 Minutes
10:01
Coding with John
Рет қаралды 943 М.
Thread Pools in Java
18:04
Jakob Jenkov
Рет қаралды 68 М.
🕊️Valera🕊️
00:34
DO$HIK
Рет қаралды 15 МЛН