9:00 Stopping threads Synchronized keyword will stop threads executing the method concurrently but if a new 2nd object is created, then two different threads can call the method concurrently on each of the object instances. So synchronized only works if multiple threads call same object 8:30 the native way of stopping a thread will stop a thread in an unkown state. Implement a runnable that has a stop function instead of using the default stop method. The custom stop function sets a stop requested variable, then the runnable run method can keep checking if a stop has been requested or not and terminate on its own terms (saving any state before stopping). 12:00 the main thread can terminate, but as long as any of the threads it started are still running, then the JVM will stay running. Daemon threads will NOT keep the jvm alive if they are the last thread running, so if you want the jvm to stop running after all other threads have terminated thread.setDaemon(true) 14:10 can make main thread wait for another thread by using thread.join 15:15 OS threads vs more lightweight threads project loom (fibers)
I have to thank you for the fantastic work you do here. This video (along with the related article) both summarized and was more informative than the last three lectures on multithreading in my comp-sci course. People like you make learning easy, and are a real gift to the world.
God of Concurency..i have bene flowing you since my 2014 when you used to write blog post only...by going through your post i attend interview like a LION when they ask mutithreading qns....Thanks a Lot form 10+ yrs exp guy from BLR,India.
I appreciate your tutorials. They are really helpful as I had no clue during the lecture haha. Also, your videos are very well organized and concise unlike many other videos. Thank you!
Thanks for your effort. I also like watching your textual tutorials. As a fresh Java Programmer, I acquired more new knowledge from your tutorial. Thanks a lot!
I am linking this TH-cam page to my class in a discussion about Violent Deaths and threads and not using the variable for Java thread. This is a great example of some of the information we are covering. Great Job on explaining.
@@JakobJenkov we are going over Creating threads and we were going over Violent stops using just a stop method() and why not yo use it. We are also going over starting Java Threads
for 3 days I'm looking for a person who can explain what is this thread and how I can use it, finally I understand it, you are really amazing how you make it very simple, keep going and never stop, thank you very much for your effort.
I am glad my video helped you! :-) ... nothing more frustrating than browsing / googling around for answers to a problem that you know lots of other people have the answer to, but you just can't find it. Believe me - I have tried that a lot during my 20+ years as a Java developer :-D
Hi @@JakobJenkov, I have question please, the Thread in Android has something called Handler, is this Handler is used in Java? if it's, and you cover it please show me in which video.
Jakob, I am Latino and I have to tell you that you are the best and most detailed in explaining. I am super grateful to be able to learn from your videos and website. Graciass!!
@@JakobJenkov I'm learning from Hyperskill by JetBrains and often when some topic is hard or not enough elaborated or sometimes vague described peoples putting references to your and baeldung sites :) It's almost always makes things clear, you have gift to explain hard topics. As Aristotle said "Teaching is the highest form of understanding." You got it :) Thanks a lot for your job!
Fantastic Playlist!! Hope you'll continue making these awesome videos!! Your website and content there is superb as well !! One thing, Is there a git repo for the code snippets etc. used in this playlist? It will be much helpful.
Hi Jakob, thanks for your clear explanations - while I still can't get my head around this I believe I may need to take things a little slower in order to fully understand your code examples. Nevertheless, thank you for your explanations and keep it up! :)
Locks (and synchronized blocks) also effect the memory barrier. In other words, locking and unlocking a lock will have the same effect as entering and exiting a synchronized block - which causes the updates to the variables to be visible to other threads.
Still great! Thanks. One small thing. I added print to main method after calling run of thread and now voiala you can see main thread is finished but thread still runs and shows its print
Great! ... will try to publish more videos in the future, but I don't have as much time at the moment as I used to... but I am recording a video right now, so I will release a new video soon!
Well, if the thread calling join() is kept alive (not terminating) as long as the daemon thread is running - what could happen? ("what could possibly go wrong?" :-D )
Does the textual version include all the informations that TH-cam course have(I mean for entire JAVA THREADS, not just for this episode)? I prefer textual version more but I dont want to miss any bit of what YT course gives. Thanks for the answer!
Adding the synchronized keyword on both flag control methods ensures immediate stopping of threads that share the same runnable (no more printing)(t2,t1,t1,t2,t2,stop) and removing them will allow an extra sout to be printed even after stopping (t2,t1,t1,stop,t1,t2) If you synchronize the runnable sleep() method, this will ensure each thread prints a statement in an orderly fashion (t1, t2, t1, t2, t1,stop). If you synchronize the run() method itself, then one thread will be printing statements as it's not gonna leave the shared resource at all(t1,t1,t1,t1...stop).
If your Runnable instance has any member variables, those would be shared among the threads running that instance. Most often you do not want to do that. You want each thread to have its own Runnable instance (at least that is the most common use I have seen).
calling interrupt() on a thread only works if A) The thread is blocked somewhere e.g. in a wait() call which respects the interrupt signal. B) The thread does itself check its own interrupt signal. While I could have used the interrupted flag on a thread to signal it to stop, I prefer making the signals more explicit. This way you know that the stop signal does not mean it should immediately abort everything it does *in the middle of its loop*, but can do so *at the boundaries (beginning) of its loop*. There is a slight difference there, although I understand it can be hard to see it until you know its there :-)
Can you provide an example where 2 threads calls requestStop() or/and isStopRequested() at the same time? I can't think of an example since it is the runnable which calls the method, not the thread, which leads to another question, why do we need the synchronized keyword here?
if the stopRequested variable is a member variable of the Runnable implementation, then yes, the threads will share that member variable. Thus, when one thread is requested to stop, the other thread will stop too. Normally you do not pass the same Runnable implementation to different threads, because you often have some control logic inside them that you want to be controllable for each thread. Rather, if the threads are to share objects, these objects are accessed from inside the Runnable implementations.
Hey Jakob, massive thanks for the help! I do, however, wonder how come the ... are still printed after the printing of "stop requested". How would one be able to prevent this from happening?
You would normally delegate the work you have to do to a background thread, rather than executing it directly in the UI thread. When the background thread finishes its work, the last thing it does it to send a message back to the UI thread with the result. I have described how you do that in JavaFX (see link below). I will be similar in other UI toolkits such as Java Swing, Java AWT or SWT. tutorials.jenkov.com/javafx/concurrency.html
Fantastic playlist and great info, thank you so much, your other website has so much amazing information. I only have one question about best practices and organising code that will be multi-threaded. Most of the time, I would implement a runnable interface, or use a lambda/method reference. If I have some long running task simulating processing lots of data etc.. Should the core logic be inside the run method or should the run method be in a separate class that only deals with the logic of handling threads. Because I may a split a task between multiple threads ? For example, If I get some data from a database or an api, then I have a huge list of data that i want to process, say I have a method called processData, should that logic be inside run or should i call processData from run ? Just wanted to know if there are any best practices to organising this. Also server side multi-threading seems to be different ? Because there is no main UI thread or UI rendering server side, I guess it would just be large computations ? Making a request to a DB could be on the main thread itself ? Especially as it sequential ? In order to respond to a request, I would need to wait for database to respond anyway, I am so sorry i just had one question about organising multithreaded code but went on a tangent, Your videos and online tutorials are so helpful Thank you
Sorry about the late reply! ... I would keep the run() method as small as possible, and move the application logic to separate classes / objects. On the server - it depends on the threading model used by the web server you are using. If the web server uses one thread per connection, you can block that thread and call a database or remote HTTP / REST API from inside that thread. However, if the web server uses a single-threaded design (as Netty or Undertow does), then you should NOT call a database or remote HTTP / REST API from that thread, but instead call that from a background thread, so you don't block the single thread serving requests from the users.
When using lambda expression to create a new thread, isn't it more readable to implement Runnable interface like the following code snippet? Thread thread = new Thread ( () -> { System.out.println("Lambda running"); System.out.println("Lambda finished"); } ); thread.start(); Anyways, thanks for making this awesome multithreading series. High quality content!
Great video! Is there and easy way how to explain difference in Java vs Python threading module? As Python thanks to GIL is single threaded what does it mean in comparison to the Java? In other words what is possible to achieve with java that is not possible with python in terms of multithreading? Thanks!
9:00
Stopping threads
Synchronized keyword will stop threads executing the method concurrently but if a new 2nd object is created, then two different threads can call the method concurrently on each of the object instances. So synchronized only works if multiple threads call same object
8:30 the native way of stopping a thread will stop a thread in an unkown state. Implement a runnable that has a stop function instead of using the default stop method. The custom stop function sets a stop requested variable, then the runnable run method can keep checking if a stop has been requested or not and terminate on its own terms (saving any state before stopping).
12:00 the main thread can terminate, but as long as any of the threads it started are still running, then the JVM will stay running. Daemon threads will NOT keep the jvm alive if they are the last thread running, so if you want the jvm to stop running after all other threads have terminated thread.setDaemon(true)
14:10 can make main thread wait for another thread by using thread.join
15:15 OS threads vs more lightweight threads project loom (fibers)
hey Jakob. I usually give a visit to your webiste at work on a weekly basis. just wanted to say thanks for the effort. It has helped me a lot at work
You are welcome :-) Happy my tutorials help people out there :-)
I just don't have words to express all my gratitude for all your work
Thank you! :-) The words you did have are still very much appreciated :-)
Thank you for creating all of these high quality videos - a very valuable resource
You are welcome ! :-)
Loved it, threads have always been hard to grasp but you made it way easier
Great ! 😊
This playlist is a jackpot for learning concurrency in Java, thanks for creating these
Great ! Thanks :-)
I have to thank you for the fantastic work you do here. This video (along with the related article) both summarized and was more informative than the last three lectures on multithreading in my comp-sci course. People like you make learning easy, and are a real gift to the world.
Thank you very much! - and I am happy that my tutorials have helped you learn!
The clarity, conciseness and simplicity of your videos and articles are a immense contribution for tech!! Thank you so much for your effort!!
Thank you very much for your kind words! :-)
God of Concurency..i have bene flowing you since my 2014 when you used to write blog post only...by going through your post i attend interview like a LION when they ask mutithreading qns....Thanks a Lot form 10+ yrs exp guy from BLR,India.
Thanks! :-)
Thank you for this amazing tutorial that explains a lot of important concepts related to Threading in Java. Much appreciated.
You are welcome !! 😊 Happy it was helpful to you !! 😊
I appreciate your tutorials. They are really helpful as I had no clue during the lecture haha. Also, your videos are very well organized and concise unlike many other videos. Thank you!
You are welcome! ... and thank you for taking the time to tell me! :-)
Thanks for your effort. I also like watching your textual tutorials. As a fresh Java Programmer, I acquired more new knowledge from your tutorial. Thanks a lot!
Thanks! - Great to hear :-)
Another awesome video, thanks Jakob!👏
You are welcome! :-)
thanks, this series is much better then reading the boring "java concurrency" book
short and to the point examples you can follow along, 10/10
Thanks :-D ... I hope my voice doesn't make you fall asleep :-D
I am linking this TH-cam page to my class in a discussion about Violent Deaths and threads and not using the variable for Java thread. This is a great example of some of the information we are covering. Great Job on explaining.
I am not sure I understand exactly what your class is about?
@@JakobJenkov we are going over Creating threads and we were going over Violent stops using just a stop method() and why not yo use it. We are also going over starting Java Threads
THANK YOU so much. This solved a "freezing" issue when I was trying to use media in my JSwing. So helpful!
Great ;-)
for 3 days I'm looking for a person who can explain what is this thread and how I can use it, finally I understand it, you are really amazing how you make it very simple, keep going and never stop, thank you very much for your effort.
I am glad my video helped you! :-) ... nothing more frustrating than browsing / googling around for answers to a problem that you know lots of other people have the answer to, but you just can't find it. Believe me - I have tried that a lot during my 20+ years as a Java developer :-D
Hi @@JakobJenkov, I have question please, the Thread in Android has something called Handler, is this Handler is used in Java? if it's, and you cover it please show me in which video.
Amazing! I have an interview for a job that specializes threads, and your video is HEAVEN sent :D
Great timing :-)
Jakob, I am Latino and I have to tell you that you are the best and most detailed in explaining. I am super grateful to be able to learn from your videos and website. Graciass!!
Thank you very much! :-) I am happy that my videos are helpful for you! :-)
Hello Jakob.. Loved this simple and straight to the point tutorial. Thank you for making this!
Cool - you are welcome :-)
Lots of love from the bottom of my heart
You are welcome! I am glad my tutorials help people out there! :-)
Exceptional tutorial. Very clearly explained & well-organized examples!
Thank you! :-)
So obvious, so clear. Great job!
Thanks - glad it was easy to understand! :-)
@@JakobJenkov I'm learning from Hyperskill by JetBrains and often when some topic is hard or not enough elaborated or sometimes vague described peoples putting references to your and baeldung sites :)
It's almost always makes things clear, you have gift to explain hard topics. As Aristotle said "Teaching is the highest form of understanding." You got it :)
Thanks a lot for your job!
You are welcome !! Glad my tutorials are helpful to people out there ! :-)
this is just awesome , Jenkov .. i usually go through your website ..thank you very much for sharing knowelege at diamond level !
Hi Subbu! Thank you for your kind words! I am happy that my articles and videos are helpful for you! :-)
Good to have a revision on this concept. Thanks for you effort.
Ah, so you noticed that this video replaces an older video I've made on this topic?? ... which had text flickering, and covered less topics etc. ;-)
Your videos are just outstanding..I feel more confident in java concurrency now..thanks
Thank you very much !! I have more videos on Java concurrency coming soon !!
thanks a lot sir for your generosity, i learn a lot from your courses, big hug for you :)
Glad to be able to help :-)
12:18 "And keeps the Java Virtual Machine ~alive~", says he, as if he was a mad scientist.
Jokes aside, wonderful videos! It's been of great help :))
;-)
Very nice educational videos. I like how you explain things, understandable language and powerful examples! Well done Jakob!
Thank you very much! :-)
Thanks Jakob, incredible teacher.
You are welcome :-)
Jakob, this was an amazing explanation. Thanks a lot :D. Subscribed!
Great! And thanks! :-)
This is a fantastic video. The chapters are such a nice touch
Thanks !! 😊😊
From Saudi Arabia thx🇸🇦🇸🇦🇸🇦 u help me to understand well my lessons
You are welcome :-)
very straightforward !! amazing
I try my best to make the content easy to understand :-)
Thank you! Amazing tutorial and easy to follow!
Thank you - glad it was helpful! :-)
Thank you for these well explained videos :)
You're very welcome! :-)
Awesome as usual 👍
Thanks! :-)
Excellent video, great job, thanks!
Thanks - glad you liked it! :-)
Thanks for your explanation.
You are welcome
Thank man I learn something from you.
You are welcome ! :-)
Thanks for your video. It was amazing a bring a lot a knowledge !
Thanks!! Glad you liked it !! 😊
Much Appreciated! Helped a lot.
Great - glad it helped! :-)
Great instruction!
Thank you very much !!!
Such a good tutorial!
Great to hear it is helpful for you! :-)
Fantastic Playlist!!
Hope you'll continue making these awesome videos!!
Your website and content there is superb as well !!
One thing, Is there a git repo for the code snippets etc. used in this playlist? It will be much helpful.
Great explanation!
Glad it was helpful ! :-)
thank you. there course is helping insane!
Thank you 😊😊
Hi Jakob, thanks for your clear explanations - while I still can't get my head around this I believe I may need to take things a little slower in order to fully understand your code examples. Nevertheless, thank you for your explanations and keep it up! :)
Thanks ! ... what exactly can't your get your head around?
Thanks a lot i was struggling with that !!
You are welcome! :-)
Great Content for Java Concurrency
Thanks, Joseph :-)
When and how the runnable stops the thread after checking the stopRequested variable?
Then the Runnable.run() method exits (returns) - meaning it simply finishes executing - then the Thread executing the Runnable stops automatically.
GREAT TUTORIAL
Thank you very much! :-)
in example 8 don't you need a volatile keyword for the boolean? race conditions is fixed by the locks but is the memory barrier fix missing?
Locks (and synchronized blocks) also effect the memory barrier. In other words, locking and unlocking a lock will have the same effect as entering and exiting a synchronized block - which causes the updates to the variables to be visible to other threads.
This is great!
Thanks! :-)
Greeeeat explanation!
Thanks :-)
Still great! Thanks. One small thing. I added print to main method after calling run of thread and now voiala you can see main thread is finished but thread still runs and shows its print
this really helps thx a lot keep it up!
Great! ... will try to publish more videos in the future, but I don't have as much time at the moment as I used to... but I am recording a video right now, so I will release a new video soon!
14:15 Isn't it using .join( ) on a daemon thread a bad idea?
Well, if the thread calling join() is kept alive (not terminating) as long as the daemon thread is running - what could happen?
("what could possibly go wrong?" :-D )
Hey Jakob! Thanks a ton for these Amazing lectures! Your explanations are very clear.
Btw, do you plan on making videos about Java Futures?
Thanks ! Yes, at some point I will get to Java Future too !
Thanks Jakob! Videos on CompletableFutures in Java would be great!
Does the textual version include all the informations that TH-cam course have(I mean for entire JAVA THREADS, not just for this episode)? I prefer textual version more but I dont want to miss any bit of what YT course gives. Thanks for the answer!
Usually the articles and videos have the same amount of details 😊
@@JakobJenkov thank you 👍🏻
Very informative!
Thanks ! :-)
Good stuff, just stumbled upon you Jakob.
Thank you ! :-) Glad you liked my videos :-)
Thanks, nice video.
You are welcome! Glad you liked it! :-)
Adding the synchronized keyword on both flag control methods ensures immediate stopping of threads that share the same runnable (no more printing)(t2,t1,t1,t2,t2,stop) and removing them will allow an extra sout to be printed even after stopping (t2,t1,t1,stop,t1,t2)
If you synchronize the runnable sleep() method, this will ensure each thread prints a statement in an orderly fashion (t1, t2, t1, t2, t1,stop).
If you synchronize the run() method itself, then one thread will be printing statements as it's not gonna leave the shared resource at all(t1,t1,t1,t1...stop).
Are there pros and cons in using the same runnable instance to instanciate multiple threads?
If your Runnable instance has any member variables, those would be shared among the threads running that instance. Most often you do not want to do that. You want each thread to have its own Runnable instance (at least that is the most common use I have seen).
@@JakobJenkov Thanks, I understood that better when I watched your video on the Java memory model.
It is amazing continue
Thank you 😊
Good stuff thanks to your blogs my understanding of concurrency is clear
Great - that makes me happy to hear ! :-) I have more videos on Java Concurrency coming !
Why do you create stoppable runnable to stop if the same effect can be done with interrupt, but interrupt is better in all ways?
calling interrupt() on a thread only works if
A) The thread is blocked somewhere e.g. in a wait() call which respects the interrupt signal.
B) The thread does itself check its own interrupt signal.
While I could have used the interrupted flag on a thread to signal it to stop, I prefer making the signals more explicit.
This way you know that the stop signal does not mean it should immediately abort everything it does *in the middle of its loop*,
but can do so *at the boundaries (beginning) of its loop*. There is a slight difference there, although I understand it can be hard to see it until you know its there :-)
Can you provide an example where 2 threads calls requestStop() or/and isStopRequested() at the same time? I can't think of an example since it is the runnable which calls the method, not the thread, which leads to another question, why do we need the synchronized keyword here?
if the stopRequested variable is a member variable of the Runnable implementation, then yes, the threads will share that member variable. Thus, when one thread is requested to stop, the other thread will stop too. Normally you do not pass the same Runnable implementation to different threads, because you often have some control logic inside them that you want to be controllable for each thread. Rather, if the threads are to share objects, these objects are accessed from inside the Runnable implementations.
@@JakobJenkov Thank you
creating an accesses functions for the inserting and the updating functions that can be callable outside the jar
I don't think I understand what you mean?
Hey Jakob, massive thanks for the help! I do, however, wonder how come the ... are still printed after the printing of "stop requested". How would one be able to prevent this from happening?
if you'd like to prevent this behaviour you'd basically need some sort of shared boolean variable between the two threads and do stuff according to it
how to stop freezing ui using multithreading using java
You would normally delegate the work you have to do to a background thread, rather than executing it directly in the UI thread. When the background thread finishes its work, the last thing it does it to send a message back to the UI thread with the result. I have described how you do that in JavaFX (see link below). I will be similar in other UI toolkits such as Java Swing, Java AWT or SWT.
tutorials.jenkov.com/javafx/concurrency.html
Fantastic playlist and great info, thank you so much, your other website has so much amazing information. I only have one question about best practices and organising code that will be multi-threaded. Most of the time, I would implement a runnable interface, or use a lambda/method reference.
If I have some long running task simulating processing lots of data etc.. Should the core logic be inside the run method or should the run method be in a separate class that only deals with the logic of handling threads.
Because I may a split a task between multiple threads ?
For example, If I get some data from a database or an api, then I have a huge list of data that i want to process, say I have a method called processData, should that logic be inside run or should i call processData from run ?
Just wanted to know if there are any best practices to organising this.
Also server side multi-threading seems to be different ? Because there is no main UI thread or UI rendering server side,
I guess it would just be large computations ?
Making a request to a DB could be on the main thread itself ? Especially as it sequential ? In order to respond to a request, I would need to wait for database to respond anyway,
I am so sorry i just had one question about organising multithreaded code but went on a tangent, Your videos and online tutorials are so helpful
Thank you
Sorry about the late reply! ... I would keep the run() method as small as possible, and move the application logic to separate classes / objects.
On the server - it depends on the threading model used by the web server you are using. If the web server uses one thread per connection, you can block that thread and call a database or remote HTTP / REST API from inside that thread. However, if the web server uses a single-threaded design (as Netty or Undertow does), then you should NOT call a database or remote HTTP / REST API from that thread, but instead call that from a background thread, so you don't block the single thread serving requests from the users.
Very good, thank you sir
You are very welcome :-)
great explication thank you
You are welcome!
Thanks a lot, but do you have GitHub source, so we can practice with you
The Java examples I have in GitHub are found in this repo:
github.com/jjenkov/java-examples
@@JakobJenkov cool, but it doesn't have this video's code, so I have uploaded in your repo
@@heclosty-wk3bj
@JakobJenkov Can you merge his PR?
Thank you very much❤️
You're welcome 😊
When using lambda expression to create a new thread, isn't it more readable to implement Runnable interface like the following code snippet?
Thread thread = new Thread ( () -> {
System.out.println("Lambda running");
System.out.println("Lambda finished");
} );
thread.start();
Anyways, thanks for making this awesome multithreading series. High quality content!
That is a question of personal style preference. Your way can work just fine too :-)
Great video! Is there and easy way how to explain difference in Java vs Python threading module? As Python thanks to GIL is single threaded what does it mean in comparison to the Java? In other words what is possible to achieve with java that is not possible with python in terms of multithreading? Thanks!
Hi Matus, I don't know Python well enough at this point to say what the difference between Java threads and Python threads are, unfortunately.
great video
Thank you very much! :-)
thank you Jakob
You are welcome! :-)
Thanks 👍❤️
You're welcome 😊
Great videos, thanks!
Are there source codes?
There are some, here:
github.com/jjenkov/java-examples
Thank you for saving me from those dry technical books.
You are welcome ! ;-)
thanccc
You are welcome :-)
thank's
You are welcome :-)
"Oh and one final thing..." - goes on to casually give the best explanation of project loom and virtual threads I have heard. In a couple of seconds.
Thanks :-) :-)
Thanks
Welcome :-)
bro randomly went to another level idk what is happening
Whar do you mean ? 😊