Solved

Multithreading

Posted on 2004-08-19
9
259 Views
Last Modified: 2010-03-31
I have a helper class , whose method i invoke . The problem is that method can take upto 15 sec to finish. But i only want to wait 10 sec...if it doesnt return in 10 sec...i would like to kill that method call.


I am thinking i have to spawn new threads...one for the method call...another to keep track of time.....
Can someone tell me how to accomplish this.
Pappu
0
Comment
Question by:rahulkothari
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 35

Accepted Solution

by:
TimYates earned 125 total points
ID: 11841557
Does:

   thread.join( 10000 ) ;
   if( thread.isAlive() )
        thread.interrupt() ;

work?
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11841583
use the javax.swing.Timer

Timer timer = new Timer([int delay], [ActionListener al]);
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11842503
what do you mean by "kill"? What is the helper method doing for the 15 seconds? It might be likely that that task might not be capable of being stopped, in which case you'll just have to ignore it, and continue as if its not running (if you have control of the code, it might be possible to put in code that will allow it to be stopped (e.g. a "stillRunning" boolean method checked in a loop, if there is a loop, or if its IO, the stream might be closable, etc... really depends on what is going on in the helper method...
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 

Author Comment

by:rahulkothari
ID: 11842762
I did it something like this :

***************************
import java.util.*;

class test1 extends Thread
{
      public void run(){
            for (int i=0;i<=6 ;i++ )
            {
                  System.out.println("Sleeping "+ i + " second.");
                              try {
                                          long numMillisecondsToSleep = 1000; // 1 second
                                          Thread.sleep(numMillisecondsToSleep);
                                    } catch (InterruptedException e) {
                                          System.out.println("INTERUPTED");
                                          return;
                                    }
            }
      }
}

public class Test
{
      public Test(){
             try
             {
             Thread thread = new test1();
         thread.start();
             Thread.sleep(10000);
             if(thread.isAlive())thread.interrupt() ;
             }
             catch (Exception e)
             {
                   e.printStackTrace();
             }

      }
      
      public static void main(String[] args)
      {
            new Test();
      }
}
*****************************


But in this case i always sleep for 10 sec.....as you can see my sample test1 thread finishes in 6 sec......how do i avoid sleeping for that extra 4 sec in case my helper thread finishes before 10 sec. ???

Please suggest
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11842857
>> Thread.sleep(10000);

Make that a call to wait () instead of sleep ().

In the run () method, make a call to notifyAll (). Better to put it in a finally block so that it gets executed even when there is an exception and you're returning.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11842982
Use join instead of sleep (like I suggested)
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11843025
Hi,

Just to follow on from before, using "thread.interrupt()" is fine if the helper method is waiting or sleeping, - if the interrupt() is called while the other thread is working, e.g. performing some labourous processing task, the interrupt is likely not to do anything...

A test will show this:

public class Test {
    public static void main( String[] args ) throws Exception {
        Thread testthread = new Thread(
            new Runnable() {
                public void run() {
                    // dumbly spin on a counter, to simulate a busy processing task...
                    for( long i = 0; i != 1000000000; i++ ) {}
                    System.out.println( "Finished stupidly spinning" );
                    synchronized( this ) {
                        notifyAll();
                    }
                }
            } );

        System.out.println( "Starting test thread" );
        testthread.start();
        System.out.println( "Waiting for a short while!" );
        Thread.sleep( 100 );
        System.out.println( "interrupting testthread" );
        testthread.interrupt();
        System.out.println( "After the interrupt" );
        synchronized( testthread ) {
            testthread.wait();
        }
    }
}

In this case, the way around it is to provide a object boolean "stillRunning", and set it to false instead of the interrupt() - also, this boolean would have to be in the loop conditional...

As I said before, really dependant on the type of processing being done in the thread.... If you can give an idea of what is being done, a way of interrupting/abandoning it should be devisable...

Cheers,
C.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11843032
Ah, yes. join ( int ) is better.
0
 
LVL 4

Expert Comment

by:bhpr
ID: 11849986
What about this:

public class Test
{
     public Test(){
           try
           {
           Thread thread = new test1();
                  thread.start();
           //Thread.sleep(10000);
               mysleep(1000,10,thread);
           if(thread.isAlive())thread.interrupt() ;
           }
           catch (Exception e)
           {
                e.printStackTrace();
           }

     }

       private void mysleep (int msbreaksups, int times, Thread _thread) {
            while (thread.isAlive() && times > 0) {
                  try      {
                              Thread.sleep(msbreakups);
                  } catch (Exception e)      {
                        e.printStackTrace();
                  }
                  times--;
            }
       }
     
     public static void main(String[] args)
     {
          new Test();
     }
}

bhpr
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
servlet requestdispatcher include and forward differences 1 39
ForLoop Example 3 52
CSV file parsing thru Java 13 34
Html Table Looping (part 2) 5 27
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

792 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question