簡體   English   中英

如何在Java中測試IO問題?

[英]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) {
    }
}

為了進行超時測試,您實際上可以為執行測試花費最大的時間,在JUnit中,您可以包括注釋超時:

@Test(timeout=100)
public void method_withTimeout() {
       while(true);
}

對於測試方法退出的部分測試,您可以使用Future接口,該接口提供超時以獲取結果。

如果我正確理解您的問題,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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM