views:

57

answers:

2

How would I go about making a function that would do this in java.

String result = null

do
{
  SendData()

  // Run Blocking Function: ReceiveData() Until it returns a result
  // or t seconds have elapsed

  // if something returned, result = something
  // else result = null

} while(result == null);
+3  A: 

This is what I do in a similar situation,

private static final ExecutorService THREADPOOL
       = Executors.newCachedThreadPool();

private static <T> T call(Callable<T> c, long timeout, TimeUnit
timeUnit)
       throws InterruptedException, ExecutionException, TimeoutException
   {
       FutureTask<T> t = new FutureTask<T>(c);
       THREADPOOL.execute(t);
       return t.get(timeout, timeUnit);
   }

   try {
       String task = call(new Callable<String>() {
           public String call() throws Exception
           {
              String result = null
              do {
                  SendData()
              } while(result == null);          
            }, 2, TimeUnit.SECONDS);
   } catch (TimeoutException e) {
       System.err.println("Job timedout");
   }
ZZ Coder
@ZZ I am curious to know why you dont use a ScheduledExecutorService instead? http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html
John V.
I don't see how ScheduledExecutorService can be easily used for this. It's all about scheduling start of the job, no easy way to cancel it after certain period. An example will help.
ZZ Coder
A: 

If ReceiveData is talking to the network, just set a read timeout on it.

EJP