Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: is interrupting thread absolutely necessary

I am new to Java and using a code given by someone. There, at the end of the code, they interrupt a thread if it has not finished. I am measuring the timing of the code.

The problem is that the Java code first issues all the threads, and then at the end it interrupts. Is interrupting necessary? Can't we wait till all threads actually finish? Or may be just skip interrupting (these threads are running processes using process exec command and they will finish anyway). Here is the relevant code. First the code for individual thread:

  String commandString = "./script.scr ";
  process = Runtime.getRuntime().exec(commandString);
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
  while ((lsString = bufferedReader.readLine()) != null)
        {
            System.out.println(lsString);
        }       
        try
        {
            process.waitFor();
        }

Now the code of the part which dispatches these threads:

public void stopWhenAllTaskFinished()
{
    while(notFinished) {sleep(50);} //notFinished is class variable and somewhere else it will set to false. 
    //now finished.
  //Interrupt all the threads
    for (int i=0; i<nThreads; i++) {
        threads[i].interrupt();
    }
}

This function is called from main class like:

 obj.stopWhenAllTaskFinished()

I greatly appreciate any insight or answer.

like image 823
user984260 Avatar asked May 02 '12 01:05

user984260


People also ask

When should we interrupt a thread in Java?

When a thread checks for an interrupt by invoking the static method Thread. interrupted , interrupt status is cleared. The non-static isInterrupted method, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

Why should a thread be interrupted?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

When should you interrupt a thread?

interrupt() method: If any thread is in sleeping or waiting for a state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException. A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.

What happens if a thread is interrupted?

An InterruptedException is thrown when a thread is interrupted while it's waiting, sleeping, or otherwise occupied. In other words, some code has called the interrupt() method on our thread. It's a checked exception, and many blocking operations in Java can throw it.


2 Answers

The following code that Oracle provides in the javadocs is what most people do. AFAIK, this is designed to kill threads that refuse to shutdown gracefully after giving them a chance to shutdown.

http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

 void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }
like image 187
Jon7 Avatar answered Oct 11 '22 13:10

Jon7


It is not clear whether the interrupts are needed from the code that you have posted.

  • If notFinished is set to false when all threads have finished, then the interrupts are unnecessary.

  • If notFinished is set to false when there is a possibility that some threads haven't finished, then it could be necessary. Whether it is actually necessary depends on other things:

    • Are you prepared for the application to wait for the threads to finish naturally?
    • Can you be sure that the threads will finish? (Could they hang / block forever?)
    • Do you need the results of their activity?
    • Will they respond to an interrupt? (In this case, I think that the answer is "yes".)
    • Is there any harm in leaving the threads there? (For instance, does it stop the application shutting down?)
like image 39
Stephen C Avatar answered Oct 11 '22 13:10

Stephen C