Week 52 — How can one interrupt threads (in Java) and why is that useful?

Question of the Week #52
How can one interrupt threads (in Java) and why is that useful?
8 Replies
Eric McIntyre
Eric McIntyre12mo ago
When writing Java code, one shouldn't directly stop other threads as that may result in inconsistencies, unclosed resources (like files or network connections) or similar problems. Instead, threads should be stopped cooperatively meaning the thread is asked to stop and can finish all critical work before. For this, the class Thread provides the methods interrupt() which interrupts the thread (i.e. asks it to stop) and isInterrupted which checks whether a thread is interrupted.
Thread thread = new Thread(()->{
System.out.println("thread started");
while(!Thread.currentThread().isInterrupted()){//do work until the current thread is interrupted/asked to stop
//do some work here
}
System.out.println("Thread was interrupted, work is stopped");
});
thread.start();
Thread.sleep(3_000);
System.out.println("interrupt other thread");
thread.interrupt();
Thread thread = new Thread(()->{
System.out.println("thread started");
while(!Thread.currentThread().isInterrupted()){//do work until the current thread is interrupted/asked to stop
//do some work here
}
System.out.println("Thread was interrupted, work is stopped");
});
thread.start();
Thread.sleep(3_000);
System.out.println("interrupt other thread");
thread.interrupt();
Eric McIntyre
Eric McIntyre12mo ago
Many blocking methods like Thread.sleep throw an InterruptedException when the current thread is interrupted. This allows to quickly stop the work even if the current thread is stopped.
Thread thread = new Thread(()->{
System.out.println("thread started");
try{
Thread.sleep(10_000);//sleep 10 seconds, this method throws an InterruptedException if the thread is interrupted
System.out.println("sleeping finished without interruption");
}catch(InterruptedException e){
System.out.println("Thread was interrupted, we can do cleanup work here");
Thread.currentThread().interrupt();//interrupt current thread again since throwing the exception cleared the interrupt
}
});
thread.start();
Thread.sleep(3_000);
System.out.println("interrupt other thread");
thread.interrupt();
Thread thread = new Thread(()->{
System.out.println("thread started");
try{
Thread.sleep(10_000);//sleep 10 seconds, this method throws an InterruptedException if the thread is interrupted
System.out.println("sleeping finished without interruption");
}catch(InterruptedException e){
System.out.println("Thread was interrupted, we can do cleanup work here");
Thread.currentThread().interrupt();//interrupt current thread again since throwing the exception cleared the interrupt
}
});
thread.start();
Thread.sleep(3_000);
System.out.println("interrupt other thread");
thread.interrupt();
📖 Sample answer from dan1st
Eric McIntyre
Eric McIntyre12mo ago
First of all, an interrupt is a signal to an thread that it shouldn't going further in the current operation. Now, to interrupt a thread we must use an interrupt method ( interrupt() ) on this thread, and for this goal we can use a boolean flag., by defining a boolean variable to stop/kill a specifiek thread (We can call this "Stop" , "Exit") and when we want to stop this thread, this variable will have the value "true". Now, why is interrupt thread useful?? there are many reasons and I will mention some of this reasons. By using an interrupt thread: 1) we can stop a thread that is no longer needed 2) To synchronize another thread. Because is some situations we need to stop or kill a thread in order to wait another thread 3) if a specific thread blocks the main thread, then we must to interrupt this thread to avoid stopping the program we are working on.
Eric McIntyre
Eric McIntyre12mo ago
In java we can use try() catch() function to interrupt a specific thread.
Submission from ibraa6305
Eric McIntyre
Eric McIntyre12mo ago
interrupt(), it can be used when you want to stop and make a thread do something else
Submission from PNJ3.0#1519
Eric McIntyre
Eric McIntyre12mo ago
We can use the , interrupt() method and it can be useful if a thread is taking to long to get data cause it might be hanging on a infinite loop bug. Or if there is disconnect from the database so we don’t waste resources on something that will not share data.
Submission from smokeintitan
Eric McIntyre
Eric McIntyre12mo ago
Call Thread.interrupt on the main thread, it will set the interrupt bool on the thread instance to true In the threads main loop, check for the interrupt bool and return when interrupted
Submission from berrberrr
Eric McIntyre
Eric McIntyre12mo ago
Thread interruption is more of a request than a demand. Each thread has an interrupted state, which we can check inside said thread to see if we've received an interrupt request, and handle appropriately. Its dangerous to terminate a thread in the middle of operation.. what if its holding a lock? Scary! So instead we use this framework to request a thread terminate at its convenience. Another consideration is InterruptedException which many of the threads blocking methods can throw (sleep, wait, etc). In these scenarios, its still the programmers responsibility to decide how their code/thread should respond: Maybe it makes sense to propagate that exception all the way up the stack, or maybe it makes sense to handle it. That all depends on the code's goal. The final thing to keep in mind, is no matter the way a thread is interrupted, we should try and adhere to a soft-social contract that, if we're being interrupted, its probably important and we should be good citizens about it. We should attempt to conclude execution gracefully, and also log/note/return somewhere that our thread was interrupted.
⭐ Submission from fm10esk
Want results from more Discord servers?
Add your server