我有一个简单的 REST 服务,它带有一个 sleep 方法,它除了在指定的时间内以毫秒为单位休眠,然后返回一个 No Content 响应。我的 RESTTest 类尝试首先调用http://localhost:8080/myapp/rest/sleep/7500
(休眠 7.5 秒)但只等待 5 秒。5 秒后,它取消接收到的 Future(试图取消挂起的请求)并调用http://localhost:8080/myapp/rest/sleep/5000
(休眠 5 秒)并等待 5 秒。
public class RESTTest {
private final Client client = ClientBuilder.newClient();
private final ReentrantLock lock = new ReentrantLock();
private final Condition responseReceived = lock.newCondition();
public static void main(final String... arguments) {
new RESTTest().listen(10000);
}
public void listen(final long time) {
System.out.println("Listen for " + time + " ms.");
Future<Response> _response =
client.
target("http://localhost:8080/myapp/rest/sleep/" + time)).
request().
async().
get(
new InvocationCallback<Response>() {
public void completed(final Response response) {
System.out.println("COMPLETED");
lock.lock();
try {
responseReceived.signalAll();
} finally {
lock.unlock();
}
}
public void failed(final Throwable throwable) {
lock.lock();
try {
responseReceived.signalAll();
} finally {
lock.unlock();
}
}
});
lock.lock();
try {
System.out.println("Waiting for 5000 ms.");
if (!responseReceived.await(5000, TimeUnit.MILLISECONDS)) {
System.out.println("Timed out!");
_response.cancel(true);
listen(5000);
} else {
System.out.println("Response received.");
}
} catch (final InterruptedException exception) {
// Do nothing.
} finally {
lock.unlock();
}
}
}
现在我希望看到“COMPLETED”字符串只打印一次,并且“收到响应”。字符串也只打印一次。但是,“COMPLETED”字符串会打印两次!
Listen for 7500 ms.
Waiting for 5000 ms.
Timed out!
Listen for 5000 ms.
Waiting for 5000 ms.
COMPLETED
Response received.
COMPLETED
我在这里想念什么?
谢谢,