【发布时间】:2015-07-10 20:53:59
【问题描述】:
我有一种运行方法可以连接到服务器,当服务器出现故障时,会等到它收到服务器再次启动的消息。但是,这整个方法应该有一个超时,如果超时,方法应该中断并返回错误日志。
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 一起运行的进程,并根据需要在其进程上放置锁定和释放,并带有超时。我应该在想什么?其他一些并发包装器,例如执行器?
谢谢!
【问题讨论】:
-
我猜你忘了问题
-
已修复,需要指出来
-
创建线程实例来调用方法应该不会影响方法本身的设计,因此不会真正影响您的 API。
标签: java multithreading concurrency semaphore