IO与NIO –中断,超时和缓冲区

假设有一个系统有时需要将文件复制到几个位置,但是这种方式在响应速度至关重要的情况下。 换句话说,如果由于某种原因文件系统过载,并且我们无法在不到一秒钟的时间内写入文件,则应该放弃。

ExecutorService是一项非常方便的工作工具。 您可以轻松地将其用于并行执行多个任务(每个任务都写入不同的文件系统)。 Yuo还可以告诉它在超时后放弃,它将为您打断他们。 完美,正是我们所需要的。

脚手架看起来像这样:

void testCopy() throws Exception {
 ThreadPoolExecutor exec = (ThreadPoolExecutor) Executors
   .newCachedThreadPool();
 final long start = System.currentTimeMillis();
 Callable<Object> task = new Callable<Object>() {
  @Override
  public Object call() throws Exception {
   try {
    copy("a.bin", "b.bin");
   } catch (Exception e) {
    e.printStackTrace();
   }
   System.out.println("Call really finished after: "
     + (System.currentTimeMillis() - start));
   return null;
  }
 };
 Collection<Callable<Object>> taskWrapper = Arrays.asList(task);
 List<Future<Object>> futures = exec.invokeAll(taskWrapper, 50,
   TimeUnit.MILLISECONDS);
 System.out.println("invokeAll finished after: "
   + (System.currentTimeMillis() - start));
 System.out.println("Future.isCancelled? "
   + futures.get(0).isCancelled());
 Thread.sleep(20);
 System.out.println("Threads still active: " + exec.getActiveCount());
}

为了在低负载的运行状况良好的系统上模拟对超时的响应,我使用了100 MB的文件并且超时非常短。 任务总是超时,我的系统无法在50毫秒内复制100 MB。

我期望得到以下结果:

  1. 大约50毫秒后, invokeAll完成。
  2. Future.isCancelled? 是真的。
  3. 活动线程计数为0。通过睡眠可以消除某些边缘情况。 长话短说,它给了复制功能一些时间来检测中断。
  4. 通话大约在50毫秒后真正结束。 这非常重要,我绝对不希望取消任务后继续执行IO操作。 在较高的负载下,这会导致过多的线程卡在虚假的IO中。

以防万一,这些测试是在64位Windows 7上的Oracle 1.6 JVM上运行的。

解决方案1:流复制

第一次尝试可能很简单-使用带有缓冲区和经典IO的循环,如下所示:

private void copy(String in, String out) throws Exception {
 FileInputStream fin = new FileInputStream(in);
 FileOutputStream fout = new FileOutputStream(out);

 byte[] buf = new byte[4096];
 int read;
 while ((read = fin.read(buf)) > -1) {
  fout.write(buf, 0, read);
 }

 fin.close();
 fout.close();
}

这就是所有流行的流复制库做的,包括IOUtils Apache的共享和ByteStreams番石榴。

它也不幸地失败了:

invokeAll finished after: 53
Future.isCancelled? true
Threads still active: 1
Call really finished after: 338

原因很明显:在循环中或任何地方都不检查线程中断状态,因此线程可以正常继续。

解决方案2:通过复制检查流是否中断

让我们解决这个问题! 一种方法是:

while ((read = fin.read(buf)) > -1) {
 fout.write(buf, 0, read);
 if (Thread.interrupted()) {
  throw new IOException("Thread interrupted, cancelling");
 }
}

现在可以正常工作了,打印:

invokeAll finished after: 52
java.io.IOException: Thread interrupted, cancelling
 at TransferTest.copyInterruptingStream(TransferTest.java:75)
 at TransferTest.access$0(TransferTest.java:66)
 at TransferTest$1.call(TransferTest.java:25)
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
 at java.util.concurrent.FutureTask.run(FutureTask.java:138)
 at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)Future.isCancelled? true
 at java.lang.Thread.run(Thread.java:662)

Call really finished after: 53
Threads still active: 0

很好,但是我觉得不满意。 它看起来很脏,我对自己的IO库中的这段代码并不特别满意。 必须有更好的方法,这将我们带到……

解决方案3:带传输的NIO

NIO具有这个不错的功能,它实际上尊重线程中断。 如果在线程中断后尝试读取或写入通道,则会收到ClosedByInterruptException

那正是我所需要的。 由于某种原因,我还在StackOverflow上阅读了以下答案

“如果不需要,请不要使用缓冲区。 如果目标是其他磁盘或NIC,为什么还要复制到内存中? 对于较大的文件,确保的延迟是不平凡的。 (…)使用FileChannel.transferTo()FileChannel.transferFrom() 。 此处的主要优势在于,JVM使用操作系统对DMA(直接内存访问)的访问(如果存在)。 (这取决于实现方式,但是可以在通用CPU上使用现代的Sun和IBM版本。)发生的情况是,数据直接通过/从磁盘,到总线,再到目的地……直接通过RAM传递任何电路或CPU。”

太好了,让我们做吧!

private void copy(String in, String out) throws Exception {
 FileChannel fin = new FileInputStream(in).getChannel();
 FileChannel fout = new FileOutputStream(out).getChannel();

 fout.transferFrom(fin, 0, new File(in).length());

 fin.close();
 fout.close();
}

输出:

invokeAll finished after: 52
Future.isCancelled? true
Threads still active: 1
java.nio.channels.ClosedByInterruptException
 at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:184)
 at sun.nio.ch.FileChannelImpl.size(FileChannelImpl.java:304)
 at sun.nio.ch.FileChannelImpl.transferFrom(FileChannelImpl.java:587)
 at TransferTest.copyNioTransfer(TransferTest.java:91)
 at TransferTest.access$0(TransferTest.java:87)
 at TransferTest$1.call(TransferTest.java:27)
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
 at java.util.concurrent.FutureTask.run(FutureTask.java:138)
 at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
 at java.lang.Thread.run(Thread.java:662)
Call really finished after: 146

我所要做的只是简单地调用transferFrom 。 非常简洁,并承诺会从硬件和操作系统中获得如此多的支持……但是请稍等一下,为什么要花146毫秒? 我的意思是,146毫秒比第一次测试中的338毫秒快得多,但是我希望它在50毫秒后终止。

让我们在更大的文件(大约1.5 GB)上重复测试:

invokeAll finished after: 9012
Future.isCancelled? true
Threads still active: 1
java.nio.channels.ClosedByInterruptException
 at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:184)
 (...)
Call really finished after: 9170

那有多可怕? 这可能是可能发生的最糟糕的事情:

  • 任务未及时中断。 9秒太长了,我预计大约50毫秒。
  • 在整个操作过程中(9秒), invokeAll被阻止。 我勒个去?

解决方案4 –带缓冲的NIO

事实证明,我确实需要一些缓冲。 让我们尝试一下:

private void copyNioBuffered(String in, String out) throws Exception {
 FileChannel fin = new FileInputStream(in).getChannel();
 FileChannel fout = new FileOutputStream(out).getChannel();

 ByteBuffer buff = ByteBuffer.allocate(4096);
 while (fin.read(buff) != -1 || buff.position() > 0) {
  buff.flip();
  fout.write(buff);
  buff.compact();
 }

 fin.close();
 fout.close();
}

输出:

invokeAll finished after: 52
Future.isCancelled? true
java.nio.channels.ClosedByInterruptException
 at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:184)
 at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:203)
 at TransferTest.copyNioBuffered(TransferTest.java:105)
 at TransferTest.access$0(TransferTest.java:98)
 at TransferTest$1.call(TransferTest.java:29)
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
 at java.util.concurrent.FutureTask.run(FutureTask.java:138)
 at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
 at java.lang.Thread.run(Thread.java:662)
Call really finished after: 55
Threads still active: 0

现在正是我所需要的。 它本身就考虑到中断,因此我不需要整个IO实用程序进行那些繁琐的检查。 怪癖:不同类型的频道

如果我的IO实用程序仅用于复制按名称获取的文件,如下所示:

static public void copy(String source, String destination)

…然后很容易为NIO重写方法。

但是,如果它是在流上运行的更通用的签名,该怎么办?

static public void copy(InputStream source, OutputStream destination)

NIO有一个Channels实用程序,它具有非常有用的方法,例如:

public static ReadableByteChannel newChannel(InputStream in)
public static WritableByteChannel newChannel(OutputStream out)

因此,似乎我们可以使用此帮助程序包装流并从可中断的NIO API中受益。 在我们查看源代码之前:

public static WritableByteChannel newChannel(final OutputStream out) {
 if (out == null) {
     throw new NullPointerException();
 }

 if (out instanceof FileOutputStream &&
  FileOutputStream.class.equals(out.getClass())) {
  return ((FileOutputStream)out).getChannel();
 }

 return new WritableByteChannelImpl(out);
}

private static class WritableByteChannelImpl
 extends AbstractInterruptibleChannel // Not really interruptible
 implements WritableByteChannel
{
// ... Ignores interrupts completely

小心! 如果您的流是文件流,它们将是可中断的。 否则,您很不走运–它只是一个愚蠢的包装器,更像是API兼容性的适配器。 假设杀死,总是检查源头。

参考: IO与NIO – 松鼠博客上来自我们JCG合作伙伴 Konrad Garus的中断,超时和缓冲区


翻译自: https://www.javacodegeeks.com/2012/07/io-vs-nio-interruptions-timeouts-and.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值