?
Solved

Multithreading

Posted on 2004-08-19
9
Medium Priority
?
263 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 35

Accepted Solution

by:
TimYates earned 500 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month14 days, 12 hours left to enroll

771 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