Solved

Multithreading

Posted on 2004-08-19
9
255 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
 

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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 30

Expert Comment

by:mayankeagle
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:mayankeagle
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
The viewer will learn how to implement Singleton Design Pattern in Java.

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now