Solved

Multithreading

Posted on 2004-08-19
9
258 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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.

785 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