Java.What features of NIO do you know?

✅ Core Features of Java NIO (New I/O)


🔹 1. Channels

  • Abstraction for reading/writing data to files, sockets, etc.
  • Can be bi-directional (read + write)
  • Work with Buffers, not streams
FileChannel channel = new FileInputStream("file.txt").getChannel();

🔹 2. Buffers

  • Act as containers for data (like arrays)
  • You read into a buffer and then process it
  • Types: ByteBuffer, CharBuffer, IntBuffer, etc.
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);

🔹 3. Selectors

  • Allow single-threaded, non-blocking monitoring of multiple channels
  • Ideal for high-performance servers
Selector selector = Selector.open();
SelectableChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);

🔹 4. Non-blocking I/O

  • You can configure channels to not block — operations return immediately
  • Especially useful in networking (e.g. SocketChannel, ServerSocketChannel)

🔹 5. FileChannel

  • Allows random access to file content
  • Supports memory-mapped files, positioning, reading/writing large files efficiently

🔹 6. Memory-Mapped Files

  • Maps a file directly into memory, for fast access
  • Great for large files or performance-critical tasks
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);

🔹 7. Path and Files API (NIO.2 in Java 7)

  • Classes like Path, Files, and FileSystems
  • Easy and fluent file operations
Path path = Paths.get("example.txt");
List<String> lines = Files.readAllLines(path);

🔹 8. WatchService (File Watcher)

  • Allows you to watch directories for changes (create, delete, modify)




WatchService watcher = FileSystems.getDefault().newWatchService();
path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

🔹 9. Asynchronous I/O (NIO.2)

  • Introduced in Java 7 (AsynchronousFileChannel, AsynchronousSocketChannel)
  • Allows truly non-blocking file/network I/O with callbacks or Future

🧠 Summary Table

FeatureDescription
ChannelsBidirectional data flow
BuffersData containers for channels
SelectorsMonitor many channels with one thread
Non-blocking I/OImproves scalability and responsiveness
FileChannelRandom access, fast file handling
Memory-Mapped FilesFile in memory for blazing fast access
Path & Files API (NIO.2)Modern file system access
WatchServiceWatch for file system changes
Asynchronous I/OTruly non-blocking I/O (Java 7+)
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.