Home/Learn/Operating Systems/I/O Techniques: Polling, Interrupts & DMA

I/O Techniques: Polling, Interrupts & DMA

Intermediate
I/O & Kernel

Three I/O techniques — polling (CPU busy-waits), interrupt-driven (CPU is notified when device is ready), and DMA (device transfers data directly to memory) — trade CPU utilisation against I/O throughput.

Overview

In Programmed I/O (polling), the CPU repeatedly checks a device status register until the device is ready — simple but wastes CPU cycles. In interrupt-driven I/O, the CPU issues a request and continues other work; the device raises a hardware interrupt when done, and the kernel's interrupt handler processes the result. This is far more efficient for slow devices. DMA (Direct Memory Access) removes the CPU from data transfer entirely: the DMA controller moves data between the device and memory, interrupting the CPU only once when the transfer is complete. This is ideal for bulk transfers like disk reads and network packets. Java NIO's Selector maps directly onto the OS interrupt-driven model (epoll on Linux), and AsynchronousFileChannel demonstrates DMA-like async I/O.

Polling vs Interrupt-Driven I/O

Polling burns CPU in a tight loop checking device status. Interrupt-driven I/O uses the OS event notification mechanism. Java NIO's non-blocking Selector is the application-level equivalent of OS interrupt-driven I/O — the OS notifies the JVM when sockets are ready, and the Selector demultiplexes events to handlers without a thread per connection.

Java — NIO Selector (interrupt-driven I/O model)
import java.nio.channels.*;
import java.nio.ByteBuffer;
import java.net.InetSocketAddress;
import java.util.Set;

// Polling analogy (BAD — busy-wait):
// while (!socket.hasData()) { /* spin */ }
// data = socket.read();

// NIO Selector: OS interrupt-driven I/O surfaced to Java
// One thread handles thousands of connections via event notification
Selector selector = Selector.open();

// Open a non-blocking server socket
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false); // non-blocking mode
server.bind(new InetSocketAddress(8080));

// Register interest in ACCEPT events (OS will notify us)
server.register(selector, SelectionKey.OP_ACCEPT);

while (true) {
    // Blocks until at least one channel is ready (OS interrupt → wakes up)
    int readyCount = selector.select(); // equivalent to epoll_wait() on Linux
    if (readyCount == 0) continue;

    Set<SelectionKey> keys = selector.selectedKeys();
    for (SelectionKey key : keys) {
        if (key.isAcceptable()) {
            SocketChannel client = server.accept();
            client.configureBlocking(false);
            client.register(selector, SelectionKey.OP_READ);
            System.out.println("Client connected: " + client.getRemoteAddress());
        } else if (key.isReadable()) {
            SocketChannel client = (SocketChannel) key.channel();
            ByteBuffer buf = ByteBuffer.allocate(1024);
            int bytes = client.read(buf);
            if (bytes > 0) {
                buf.flip();
                System.out.println("Received: " + new String(buf.array(), 0, bytes));
            }
        }
    }
    keys.clear(); // must clear processed keys
}

DMA-Like Async I/O with AsynchronousFileChannel

DMA allows a controller to transfer blocks from disk to memory without CPU involvement. Java's AsynchronousFileChannel provides the equivalent at the application level: the read is initiated, control returns immediately, and a completion handler is invoked when the OS has finished the transfer (potentially using DMA at the hardware level).

Java — AsynchronousFileChannel (DMA-like async I/O)
import java.nio.channels.AsynchronousFileChannel;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.nio.file.*;
import java.util.concurrent.CountDownLatch;

Path file = Path.of("/tmp/large-data.bin");
Files.write(file, "Hello from async I/O!
".repeat(1000).getBytes());

CountDownLatch latch = new CountDownLatch(1);

// Open channel for async reads — OS may use DMA for actual transfer
try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(
        file, StandardOpenOption.READ)) {

    ByteBuffer buffer = ByteBuffer.allocate(512);

    // Initiate read — returns IMMEDIATELY (DMA analogy: CPU is not busy-waiting)
    asyncChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
        @Override
        public void completed(Integer bytesRead, ByteBuffer attachment) {
            // Called by OS thread pool when transfer is complete
            attachment.flip();
            System.out.println("Async read complete: " + bytesRead + " bytes");
            System.out.println("Data: " + new String(attachment.array(), 0, bytesRead));
            latch.countDown();
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            System.err.println("Async read failed: " + exc.getMessage());
            latch.countDown();
        }
    });

    System.out.println("Read initiated — CPU free to do other work (DMA-like)");
    latch.await(); // wait for completion in demo; production code would chain futures
}

Key Points to Remember

  • 1Polling wastes CPU cycles and is only appropriate for very fast devices where interrupt overhead exceeds benefit.
  • 2Interrupt-driven I/O allows the CPU to do useful work while waiting for slow devices like disks and networks.
  • 3DMA offloads bulk data transfer from the CPU to a dedicated controller, interrupting the CPU only on completion.
  • 4Java NIO Selector uses OS-level mechanisms (epoll on Linux, kqueue on macOS) — the same interrupt model, applied to sockets.
  • 5AsynchronousFileChannel provides non-blocking file I/O with completion callbacks, hiding DMA-level operations behind the JVM.
  • 6Context-switch overhead makes polling viable only for sub-microsecond I/O (e.g., network cards with busy-polling mode).

Interview Questions

Sign in to ask Aria
1

What is the difference between polling, interrupt-driven I/O, and DMA?

EasyAmazon
2

How does Java NIO's Selector relate to OS-level interrupt-driven I/O?

MediumGoogle
3

Why is DMA preferred over interrupt-driven I/O for bulk disk transfers?

MediumMicrosoft
4

Design a high-concurrency HTTP server in Java — which I/O model would you use and why?

HardNetflix

Ask Aria about I/O Techniques: Polling, Interrupts & DMA

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…