How can I find where was my thread interrupted? - java

I probably changed something in my project unintentionally. Now a key thread gets interrupted when it's not supposed to and isInterrupted returns true when the thread should be running.
Because nobody will find the problem for me, I'm asking for help on ways to find it. I need to find:
at best, the location where thread was actually interrupted and output it in console when the program is running
or all places where it is being interrupted in the code and comment them out one by one
Because IDE tools and debugger may play a role in my search I will add that I'm using NetBeans IDE.

You could run it under a special thread that logs the stack when it is interrupted:
// A simple process.
class Process implements Runnable {
#Override
public void run() {
try {
while (true) {
Thread.sleep(1000L);
}
} catch (InterruptedException ex) {
System.out.println("Interrupted");
}
}
}
public void test() throws InterruptedException {
Thread t = new Thread(new Process()) {
#Override
public void interrupt() {
// Log a stack trace when iterrupted.
new Exception("Where the hell did that come from!").printStackTrace(System.out);
// Pass it up the chain.
super.interrupt();
}
};
t.start();
Thread.sleep(2048);
t.interrupt();
t.join();
}

Related

Thread termination using interrupt method

I have a thread which runs a task of file parsing. Its set as a daemon thread which runs in background from tomcat startup to shutdown doing its task.
I am looking to handle thread termination upon interruption and server shutdown. I want to know if am going about correctly.
class LoadingModule{ // Thread is started from here
threadsStartMethod() {
Thread t = new Thread(FileParseTask);
t.setDaemon(true);
t.start();
}
}
Class FileParseTask implements Runnable {
#Override
public void run() {
try {
while(!Thread.currentThread.isInterrupted) {
// poll for file creation
// parse and store
}
} catch(Exception exit) {
log.error(message);
Thread.currentThread.interrupt();
}
}
}
would this cleanly exit the thread in all scenarios?
it would depend on the code inside the loop. If the code inside the loop captures the interrupted exception and recovers, you will never see it. Also generic exception "exit" hides other exceptions. Change the code so you know what hit you.
I would do the following
Class FileParseTask implements Runnable {
#Override
public void run() {
while(!Thread.currentThread.isInterrupted) {
try {
// poll for file creation
// parse and store
} catch(Exception exit) {
if (InterruptedException)
break;
else{
//
}
log.error(message);
}
}
}
}
This has worked for me with up to 2K threads with no problems

How to restart thread without using Thread.stop()?

I have a client-server application that runs the receive method to run in a separate thread. Thread is given some time to finish the job and the thread will be checked for the status.
There are occasions when the receive method will be blocked due to packet or ACK loss. If that happens, how can I stop the thread and start it again the next attempt?
As we all know, Thread.stop() is deprecated.
You can't restart a Java thread at all, with or without Thread.stop().
You have to create a new one.
You can however reuse a Runnable.
You can use interrupts to send to the thread and handle them to do a retry. Here is a sample that will start a thread that will not quit until the boolean done is set. However i'm interrupting the thread from a main thread to make it start over.
public class Runner implements Runnable {
private boolean done;
#Override
public void run() {
while (!done) {
try {
doSomeLongRunningStuff();
} catch (InterruptedException e) {
System.out.println("Interrupted..");
}
}
}
private void doSomeLongRunningStuff() throws InterruptedException {
System.out.println("Starting ... ");
Thread.sleep(300);
System.out.println("Still going ... ");
Thread.sleep(300);
done = true;
System.out.println("Done");
}
public static void main(final String[] args) throws InterruptedException {
final Thread t = new Thread(new Runner());
t.start();
Thread.sleep(500);
t.interrupt();
Thread.sleep(500);
t.interrupt();
}
}
Whether you can do it this way or not depends on what you are calling. Your framework doing the TCP connection may or may not support interrupting.
We should not restart a thread which is not valid , once thread has comepleted its execution.

Interrupted Exception is not called when class is stopped

There is a worker class which is executing the task. The code snippet is as follows:
public class Worker{
executor.execute( new Runnable() {
public void run() {
LOG.info("Task starting to execute");
try {
Thread.sleep(7000)`
}catch (InterruptedException)
LOG.info("Thread Interrupted");
}
LOG.info("Task Executed");
}
}
}
Here when i stop worker class when it is in sleep mode, as per my knowledge Interrupted Exception should be thrown. But in reality, it's not. Instead it just stops. Can someone please clarify my misconception. I have seen lots of threads related to this question, still my doubt is not clear

Alternative method to kill thread

I have been looking for ways to kill a thread and it appears this is the most popular approach
public class UsingFlagToShutdownThread extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print(".");
System.out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread");
}
public void shutdown() {
running = false;
}
public static void main(String[] args)
throws InterruptedException {
UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
t.start();
Thread.sleep(5000);
t.shutdown();
}
}
However, if in the while loop we spawn another another object which gets populated with data (say a gui that is running and updating) then how do we call back - especially considering this method might have been called several times so we have many threads with while (running) then changing the flag for one would change it for everyone?
thanks
One approach with these problems is to have a Monitor class which handles all the threads. It can start all necessary threads (possibly at different times/when necessary) and once you want to shutdown you can call a shutdown method there which interrupt all (or some) of the threads.
Also, actually calling a Threads interrupt() method is generally a nicer approach as then it will get out of blocking actions that throw InterruptedException (wait/sleep for example). Then it will set a flag that is already there in Threads (which can be checked with isInterrupted() or checked and cleared with interrupted(). For example the following code can replace your current code:
public class UsingFlagToShutdownThread extends Thread {
public void run() {
while (!isInterrupted()) {
System.out.print(".");
System.out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) { interrupt(); }
}
System.out.println("Shutting down thread");
}
public static void main(String[] args)
throws InterruptedException {
UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
t.start();
Thread.sleep(5000);
t.interrupt();
}
}
i added a utlility class which essentially had a static map and methods.
the map was of type Long id, Thread thread. I added two methods one to add to the map and one to stop the thread via the use of interrupt. This method took the id as a parameter.
I also changed my loop logic from while true, too while ! isInterrupted. Is this approach ok or is this bad programming style/convention
thanks

How can I kill a thread? without using stop();

Thread currentThread=Thread.currentThread();
public void run()
{
while(!shutdown)
{
try
{
System.out.println(currentThread.isAlive());
Thread.interrupted();
System.out.println(currentThread.isAlive());
if(currentThread.isAlive()==false)
{
shutdown=true;
}
}
catch(Exception e)
{
currentThread.interrupt();
}
}
}
});
thread.start();
The alternative to calling stop is to use interrupt to signal to the thread that you want it to finish what it's doing. (This assumes the thread you want to stop is well-behaved, if it ignores InterruptedExceptions by eating them immediately after they are thrown and doesn't check the interrupted status then you are back to using stop().)
Here's some code I wrote as an answer to a threading question here, it's an example of how thread interruption works:
public class HelloWorld {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(5000);
System.out.println("Hello World!");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
thread.start();
System.out.println("press enter to quit");
System.in.read();
thread.interrupt();
}
}
Some things to be aware of:
Interrupting causes sleep() and wait() to immediately throw, otherwise you are stuck waiting for the sleep time to pass.
Note that there is no need for a separate boolean flag.
The thread being stopped cooperates by checking the interrupted status and catching InterruptedExceptions outside the while loop (using it to exit the loop). Interruption is one place where it's ok to use an exception for flow control, that is the whole point of it.
Setting interrupt on the current thread in the catch block is technically best-practice but is overkill for this example, because there is nothing else that needs the interrupt flag set.
Some observations about the posted code:
The posted example is incomplete, but putting a reference to the current thread in an instance variable seems like a bad idea. It will get initialized to whatever thread is creating the object, not to the thread executing the run method. If the same Runnable instance is executed on more than one thread then the instance variable won't reflect the right thread most of the time.
The check for whether the thread is alive is necessarily always going to result in true (unless there's an error where the currentThread instance variable is referencing the wrong thread), Thread#isAlive is false only after the thread has finished executing, it doesn't return false just because it's been interrupted.
Calling Thread#interrupted will result in clearing the interrupt flag, and makes no sense here, especially since the return value is discarded. The point of calling Thread#interrupted is to test the state of the interrupted flag and then clear it, it's a convenience method used by things that throw InterruptedException.
Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():
Thread t = new Thread(new Runnable(){
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
// do stuff
}
}});
t.start();
// Sleep a second, and then interrupt
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
t.interrupt();
Good way to do it would be to use a boolean flag to signal the thread.
class MyRunnable implements Runnable {
public volatile boolean stopThread = false;
public void run() {
while(!stopThread) {
// Thread code here
}
}
}
Create a MyRunnable instance called myrunnable, wrap it in a new Thread instance and start the instance. When you want to flag the thread to stop, set myrunnable.stopThread = true. This way, it doesn't get stopped in the middle of something, only where we expect it to get stopped.

Categories

Resources