26

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?

user467158
  • 363
  • 4
  • 7

2 Answers2

21

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.

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.

In general only sockets and pipes truly support non-blocking I/O via select() mechanism.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Simply put, most operating systems doesn't treat regular files as something that can block - so they don't allow you explicitly set them to a non-blocking state.

nos
  • 223,662
  • 58
  • 417
  • 506
  • File I/O can only be blocking because they are considered non-blocking? What do you mean by that? In programming, every operation is blocking. – Val Jun 22 '12 at 08:33
  • 1
    @Val I agree that the wording is not the best here. In programming, not every operation is blocking (in the sense it puts the process or thread in a blocking state). What I mean is that for a regular file, the operating system level APIs assumes that read()/write()/open() and other calls on a regular file are non-blocking - a false assumption though. The regular/standard OS level APIs can not change the handle to a file from blocking to non-blocking. (which is something you can do with sockets and pipe handles). – nos Jun 22 '12 at 09:28
  • @nos The operating-system-level APIs assume that `read()/write()/open()` and other calls are *blocking*. Unclear what you're talking about. – user207421 May 23 '17 at 11:17
  • @EJP I don't think read() write() assume anything about blocking or not . You surely can make read()/write() being non-blocking for certain types of devices. I was simply saying that you cannot set or clear O_NONBLOCK(or any similar properties ) on a file descriptor that refers to a regular file and observe any difference. And that e.g. a select() call always tell you that the file descriptor is readable and writable. While a read() or write() it may block in reality, the OS still does not present any way for the programmer to have any control, knowledge or notification of it blocking – nos May 23 '17 at 12:46