learner
learner

Reputation: 625

Timeout for a method

My Program looks like below

  1. Main Program (Thread 1)
  2. Create multiple simple java threads (Thead 1.1, 1.2...)
  3. In each thread(1.1 or 1.2..) I'm doing some processing also calling one method which is sometimes is not responding(CORBA calls). I want to define timer for this method and thread(1.1 or 1.2 whoever is calling) should wait there itself till I get response or timer expired.

I have written following sample program. I don't think this is the right approach. Is there any better approach? In this prg I'm not sure when the interupt method is invoked.

public class MethodTimeout implements Runnable{

/**
 * @param args
 */

public Thread t1 = null;
public int threadnum = 0;
public static void main(String[] args) {


    for (int i=0; i<3; i++){
        MethodTimeout mt  =new MethodTimeout();
        Thread t = new Thread(mt,"thread "+(i+1));
        mt.t1 = t;
        mt.threadnum = (i+1); 
        t.start();
    }

    System.out.println("stmt after execution");
}

public Object testTimeout(){
    long startTime = System.currentTimeMillis();
    try {

        System.out.println("in side method start "+t1.getName()+" start time"+startTime);

        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    long endtime = System.currentTimeMillis();
    System.out.println("in side method end "+t1.getName()+" total time"+(endtime-startTime) );
    return null;
}


@Override
public void run() {

    Thread timeout  = new Thread (){
        public void run() {
            testTimeout();
        };
    };
    timeout.start();

    try {
        Thread.sleep(2000);
        timeout.interrupt();
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
    System.out.println(t1.getName() + " is ending");
}

}

Upvotes: 0

Views: 2569

Answers (2)

Kuldeep Jain
Kuldeep Jain

Reputation: 8598

You can also make one minor change to @Eugene's answer, that is instead of calling the shutdownNow() on the ExecutorService itself you can just call cancel(true) on the futureResult that timed out. Here is the code snippet:

public class Test {    
     public static void main(String[] args) throws Exception {
         ExecutorService service = Executors.newFixedThreadPool(2);
         Future<String> futureResult = service.submit(new MyCall());
             try{
                 String result = futureResult.get(20, TimeUnit.MILLISECONDS);
             } catch(TimeoutException timeout){
                  System.out.println("Timeout");
             } finally {
                  futureResult.cancel(true);
             }
   }

This is just to ensure that only the timed out thread is cancelled. As the shutdownNow() prevents waiting tasks from starting in addition to attempting to stop currently executing ones.

Upvotes: 0

Eugene
Eugene

Reputation: 121028

This very much sounds like you should implement Callable. This is just an example

 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;

 public class Test {    
     public static void main(String[] args) throws Exception {
         ExecutorService service = Executors.newFixedThreadPool(2);
         Future<String> futureResult = service.submit(new MyCall());
             try{
                 String result = futureResult.get(20, TimeUnit.MILLISECONDS);
             } catch(TimeoutException timeout){
                  System.out.println("Timeout");
                  service.shutdownNow();
             }
   }

   static class MyCall implements Callable<String> {
        @Override
        public String call() throws Exception {
             try{
                  //Simulate some corba work
                  Thread.sleep(1000);
             }catch(InterruptedException e){
                  Thread.currentThread().interrupt();
                  System.out.println("Shutting down the task!");
             }
                 return "The result";
        }
    }
} 

Upvotes: 1

Related Questions