java - Using both timeout and semaphore for Thread blocking -


i have method run makes connection server, , when server fails, wait until receives message server again. however, entire method should have timeout, , if on time, method should interrupt , return error log instead.

private semaphore sem = new semaphore(0); private timeunit unit = timeunit.milliseconds;  public string some_method(object params, long timeout, timeunit unit) {     long time = 0;     while(time < timeout) { // not sure timeout method         try {             //some task prone serverconnectexception             return; // returns value , exits          } catch(serverconnectexception ex) {             sem.acquire();         } catch(interruptedexception uhoh) {             system.out.println("uhoh, thread interrupted");         }         // increment time somehow     }     sem.release();     return null; // message of task incompletion } 
  • i thinking running thread containing semaphore blocks thread if there's server failure problem, cannot seem organize thread such contain semaphore contained method itself.

question: - however, method in gigantic class , making separate thread method mess entire call hierarchy whole api, don't want that. need process runs along some_method , places lock , release on processes needed, timeout. should thinking? other concurrency wrapper executor?

thanks!

semaphore doesn't seem right concurrency primitive use here, don't need utility locking, rather utility coordinate inter-thread communication.

if need communicate stream of values, typically use blocking queue, if need communicate single value, countdownlatch , variable trick. example (untested):

  public string requestwithretry(final object params, long timeout, timeunit unit) throws interruptedexception {     string[] result = new string[1];     countdownlatch latch = new countdownlatch(1);     thread t = new thread(new runnable() {       public void run() {         while (true) {           try {             result[0] = request(params);             latch.countdown();             return;           }           catch(otherexception oe) {             // ignore , retry           }           catch(interruptedexception ie) {             // task cancelled; terminate thread             return;           }         }       }     });     t.start();     try {       if (!latch.await(timeout, unit)) {         t.interrupt(); // cancel background task if timed out       }       // note returns null if timed out       return result[0];     }     catch(interruptedexception ie) {       t.interrupt(); // cancel background task       throw ie;     }   }    private string request(object params) throws otherexception, interruptedexception {     // should handle interruption cancel operation     return null;   } 

Comments