[英]How to test IO issues in Java?
在不使用休眠的模擬流(因為它們會對中斷做出反應)的情況下,如何在IO性能非常差的情況下測試應用程序代碼的行為?
例如,我要測試一個ConcurrentWrapper
實用程序,該實用程序具有用於文件IO的線程池。 它將每個操作都帶有帶有超時的invokeAll()
提交給ExecutorService
。 我不僅要確認使用ConcurrentWrapper
的調用在超時之前退出,還要確認它以某種方式使其內部ExecutorService
的線程終止(以避免泄漏)。
我需要以某種方式模擬內部線程中的慢速IO,但是要以一種可以忽略中斷的方式進行模擬(就像真正的IO一樣)。
需要澄清的一點是 :不能接受“睡眠並吞下InterruptedException
”或“睡眠,趕上InterruptedException
並返回睡眠”之類的答案。 我想測試我的代碼如何處理中斷,而這種檢測將通過處理它們本身來達到目的。
您可以通過堅持通過中斷睡眠的方式進行睡眠:
long start = System.currentTimeMillis();
long end = start + sleepTime;
for (long now = start; now < end; now = System.currentTimeMillis()) {
try {
Thread.sleep(end - now);
} catch (InterruptedException ignored) {
}
}
如果我正確理解您的問題,ReentrantLock可能會有所幫助。
final ReentrantLock lock = new ReentrantLock();
Callable<Void> c = new Callable<Void>() {
public void call() {
lock.lock();
try {
if (Thread.currentThread().isInterrupted()) {
...
}
}
finally {
lock.unlock();
}
}
}
// Submit to the pool
Future<Void> future = executorService.submit(c);
// you might want to sleep a bit to give the pool a chance
// to pull off the queue.
// Issue a cancel
future.cancel();
// Now release the lock, which should let your
// callable continue onto to the interrupted check.
lock.unlock();
請注意,“ lock”方法不會引發任何InterruptedException(盡管有一個名為“ lockInterruptible”的方法),並且如果您查看該類的代碼,它不會被捕獲和吞咽(正如您所陳述的那樣)成為你想成為的人)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.