问题描述
我想编写一个同时写入多个文件的程序;认为通过使用非阻塞模式可以使用一个线程。但FileChannel不支持非阻塞模式。有人知道为什么吗?
I wanted to write a program which writes to multiple files simultaneously; thought it will be possible with one thread by using non-blocking mode. But FileChannel does not support non-blocking mode. Does anybody know why?
推荐答案
UNIX不支持文件的非阻塞I / O,请参阅。由于Java应该(至少尝试)在所有平台上提供相同的行为, FileChannel
不实现 SelectableChannel
。
UNIX does not support non-blocking I/O for files, see Non-blocking I/O with regular files. As Java should (at least try to) provide the same behaviour on all platforms, the FileChannel
does not implement SelectableChannel
.
然而,Java 7将包含一个新的类,支持异步文件I / O,这是一个不同的非阻塞I / O的机制。其中一个实现受益于Windows上的非阻塞I / O API(请参阅。
However Java 7 will include a new AsynchronousFileChannel
class that supports asynchronous file I/O, which is a different mechanism to non-blocking I/O. One of its implementations WindowsAsynchronousFileChannelImpl
benefits from non-blocking I/O API on Windows (see Asynchronous I/O in Windows).
在此期间,您可以使用多个线程来实现同样的效果。但这已经在可在所有操作系统中移植。
In the meantime, you could use multiple threads to achieve the same effect. But this is already implemented in SimpleAsynchronousFileChannelImpl
which is portable across all operating systems.
一般只套接字和管道通过 select()
机制真正支持非阻塞I / O.
In general only sockets and pipes truly support non-blocking I/O via select()
mechanism.
@Trying评论因此:
@Trying comments thus:
在我看来,异步I / O(使用例如 Future
或 CompletionHandler
)是一种非阻塞I / O.
To my mind, asynchronous I/O (using for example Future
or a CompletionHandler
) is a form of non-blocking I/O.
- 它不会阻止线程在通道上执行
读取(...)
调用。 - 您可以使用
Future.isDone()
以避免以后阻止。
- It doesn't block the thread doing the
read(...)
call on the channel. - You can use
Future.isDone()
to avoid blocking later.
(A当然,使用 Selector
的I / O也可以是异步的...取决于你如何使用API。)
(And of course, I/O using a Selector
can be asynchronous too ... depending on how you use the API.)
相比之下,如果您读取 FileChannel
并且当前没有可用的数据,则线程会阻塞...(通常)直到数据可用。
By contrast, if you read on a FileChannel
and there is no data currently available, the thread blocks ... (typically) until data becomes available.
这篇关于为什么Java中的FileChannel不是非阻塞的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!