为线程阻塞使用超时和信号量



我有一个方法运行,使连接到服务器,当服务器失败时,将等待,直到它收到消息,服务器再次启动。但是,整个方法应该有一个超时,如果超时,方法应该中断并返回错误日志。

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 about timeout method
        try {
            //some task that is prone to ServerConnectException
            return; // returns value and exits 
        } catch(ServerConnectException ex) {
            sem.acquire();
        } catch(InterruptedException uhoh) {
            System.out.println("uhoh, thread interrupted");
        }
        // increment time somehow
    }
    sem.release();
    return null; // a message of task incompletion
}
  • 我正在考虑运行一个包含信号量的线程,如果有服务器故障问题,该信号量会阻塞线程,但我似乎无法组织线程,使其包含信号量,但由方法本身包含。

问题:-然而,该方法已经在一个巨大的类和单独的线程,只是该方法会搞砸整个调用层次结构以及整个API,所以我不想这样做。我需要一些与some_method一起运行的进程,并根据需要在其进程上放置锁和释放,并带有超时。我该怎么想?其他并发包装器,比如executor?

谢谢!

信号量似乎不是这里使用的正确的并发原语,因为您并不真正需要一个用于锁定的实用程序,而是一个帮助您协调线程间通信的实用程序。

如果你需要传递一个值流,你通常会使用阻塞队列,但是如果你需要传递一个值,CountDownLatch和一个变量就可以了。例如(未经测试):

  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 and retry
          }
          catch(InterruptedException ie) {
            // task was cancelled; terminate thread
            return;
          }
        }
      }
    });
    t.start();
    try {
      if (!latch.await(timeout, unit)) {
        t.interrupt(); // cancel the background task if timed out
      }
      // note that this returns null if timed out
      return result[0];
    }
    catch(InterruptedException ie) {
      t.interrupt(); // cancel the background task
      throw ie;
    }
  }
  private String request(Object params) throws OtherException, InterruptedException {
    // should handle interruption to cancel this operation
    return null;
  }

最新更新