0

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");
}

}

learner
  • 625
  • 2
  • 11
  • 25
  • This question might provide a workable solution for you also: http://stackoverflow.com/questions/2758612/executorservice-that-interrupts-tasks-after-a-timeout – Ed Plese Apr 25 '13 at 13:53
  • Same question [http://stackoverflow.com/questions/1164301/how-do-i-call-some-blocking-method-with-a-timeout-in-java](http://stackoverflow.com/questions/1164301/how-do-i-call-some-blocking-method-with-a-timeout-in-java) – DMEx38 Apr 25 '13 at 13:59

2 Answers2

1

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";
        }
    }
} 
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • I have already checked this Callable example tried it also but it just gives timeout feature but how to stop my running thread till it executes or timer expired. – learner Apr 25 '13 at 14:06
  • @learner what do you mean by "my running thread"? Do you want the main Thread to be blocked, until either the other thread expires on within the interval executes successfully? If so then this already happens. This call : *String result = futureResult.get(20, TimeUnit.MILLISECONDS);* is a BLOCKING call. The thread that executes it will not go any further until either: a) The timeout has happend b) The method returned before the timeout – Eugene Apr 26 '13 at 06:47
0

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.

Kuldeep Jain
  • 8,409
  • 8
  • 48
  • 73