java - Timeout for a method -
my program looks below
- main program (thread 1)
- create multiple simple java threads (thead 1.1, 1.2...)
- in each thread(1.1 or 1.2..) i'm doing processing calling 1 method not responding(corba calls). want define timer method , thread(1.1 or 1.2 whoever calling) should wait there till response or timer expired.
i have written following sample program. don't think right approach. there better approach? in prg i'm not sure when interupt method invoked.
public class methodtimeout implements runnable{ /** * @param args */ public thread t1 = null; public int threadnum = 0; public static void main(string[] args) { (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() + " ending"); }
}
this sounds should implement callable. this 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 corba work thread.sleep(1000); }catch(interruptedexception e){ thread.currentthread().interrupt(); system.out.println("shutting down task!"); } return "the result"; } } }