← All topics
Start ▶
IO and NIO
Files, streams, buffers, NIO channels and serialization.
100 questions
Level:
No questions match — try other words or turn a level back on.
1
What is the difference between a byte stream and a character stream in Java?
A byte stream (InputStream/OutputStream) works with raw bytes: images, zip files, any binary file. A character stream (Reader/Writer) turns bytes into characters through a charset and is meant for text.
2
Why do we need BufferedReader? Isn't a plain FileReader enough?
FileReader has a small byte buffer inside, but every read() is a separate expensive call, and it has no readLine(). BufferedReader pulls characters into memory in big chunks (8192 characters by default) and gives you the handy readLine() method.
3
What is try-with-resources, and what makes it better than a plain try-finally?
It is syntax that automatically closes the resources opened in the try (...) parentheses when the block ends. A resource must implement AutoCloseable; close() is called even if an exception is thrown.
4
What is the difference between java.io.File and java.nio.file.Path, and which one should you use?
File is the old API: it often hides errors by returning false, and its capabilities are limited. Path + Files (Java 7, NIO.2) give precise exceptions, symlinks, attributes and streams. In new code, use Path.
5
How can you read a small text file with a single line of code?
Files.readString(path) (Java 11+) gives you the whole file as one String, and Files.readAllLines(path) gives a list of lines. Both use UTF-8 by default and close the file themselves.
6
How do you write to the end of a file without erasing its old content?
Pass StandardOpenOption.APPEND (plus CREATE so the file is created if it doesn't exist) to Files.writeString or Files.newBufferedWriter. In the old API it is new FileWriter(file, true).
7
What are System.out, System.err and System.in?
They are the process's three standard streams: System.in is the input InputStream from the keyboard or a pipe, System.out is normal output, System.err is a separate output for errors. The last two are both PrintStreams.
8
What is the Serializable interface, and why does it have no methods at all?
Serializable is a marker interface: it tells the JVM "this object can be turned into bytes". ObjectOutputStream checks for this marker and throws NotSerializableException if it is missing.
9
What does the transient keyword do?
A field marked transient is not written during Java serialization. When the object is deserialized it gets the default value: null for objects, 0 for numbers, false for boolean.
10
What is a charset, and why should you specify it explicitly when reading a file?
A charset is the rule for turning bytes into characters (UTF-8, windows-1251, ISO-8859-1). If one charset is used when writing and another when reading, the text turns into garbage. Specifying it explicitly means the code doesn't depend on which machine it runs on.
11
Why is IOException a checked exception, and how should you catch it properly?
IO deals with the outside world: a full disk, a vanished file, a dropped network are always possible, so the compiler makes you think about this case. When you catch it, don't swallow the error: either handle it, or rethrow it upward with context.
12
What does the flush() method do, and when should you call it?
flush() forces data sitting in the buffer, not yet written, down to the underlying stream (file, socket). close() flushes by itself, so a separate call is only needed when you keep the stream open and the data has to arrive now.
13
When does InputStream.read() return -1, and what does it mean?
-1 means the end of the stream was reached (EOF) and there is no more data. When reading a single byte, read() returns a value from 0 to 255 as an int, so -1 is never confused with a real byte.
14
When do you choose Scanner, and when BufferedReader?
Scanner is a convenient parser: nextInt(), nextDouble(), it works with delimiters, but it is slow. BufferedReader is fast, gives you only lines, and you do the parsing yourself. For large volumes and server code, BufferedReader.
15
How do you create nested directories with a single call?
Files.createDirectories(path) creates all the missing directories on the path and doesn't fail if the directory already exists. Files.createDirectory creates only the last one and throws an exception if the parent is missing or the directory exists.
16
Should you check with Files.exists() before deleting a file?
You don't have to, and it can even be wrong: the file can change between the check and the delete. The right way is to call Files.deleteIfExists(path), or catch Files.delete and handle NoSuchFileException.
17
How do you list the files in a directory? What is the difference between Files.list and Files.walk?
Files.list(dir) gives only the first-level entries, while Files.walk(dir) descends recursively into all subdirectories. Both return a Stream<Path> and hold an open directory handle, so they are closed with try-with-resources.
18
What is PrintWriter, and how does it differ from BufferedWriter?
PrintWriter gives you convenient formatting methods: println, printf, format. But it does not throw IOException: errors are swallowed inside and can only be detected through checkError(). BufferedWriter throws the error openly.
19
How do you read a resource file inside a jar, and why doesn't Path work there?
You have to read a classpath file as an InputStream through getClass().getResourceAsStream("/templates/mail.html") or the ClassLoader. A file inside a jar is not a separate file on disk, so Path.of(...) or new File(...) can't find it.
20
Why are streams wrapped inside each other in Java IO, for example new BufferedReader(new InputStreamReader(in))?
java.io is built on the Decorator pattern: each class adds one job. One buffers, one turns bytes into characters, one compresses. You assemble the capabilities you need by wrapping, so there is no separate class for every combination.
21
What is the problem in this method, and how does it show up on prod?
The file stream is never closed: whether an exception is thrown or not, the file descriptor stays open. After many calls the process hits the OS limit and fails with Too many open files, unable to open a new file or socket.
22
When you read a text file created on Windows on a Linux server, an invisible `\r` is left at the end of the lines. Where does it come from, and how do you handle it?
Windows marks the end of a line with \r\n, Linux with \n. split("\n") or manual parsing leaves the \r, while BufferedReader.readLine() recognizes all three variants correctly. When writing, you have to choose the format deliberately.
23
Why is it a mistake to assume that in.read(buffer) fills the buffer completely?
read(byte[]) reads "at least one and at most the buffer length" bytes, whatever is ready right now. On network and pipes especially, data arrives in pieces. If you need exactly N bytes, use readNBytes or DataInputStream.readFully.
24
In try-with-resources, in what order are several resources closed, and what happens if close() throws an exception?
Resources are closed in reverse order of opening: the last one first. If an exception was thrown inside the block and close() throws too, the main error propagates out, and the one from close() is attached to it via getSuppressed().
25
What is serialVersionUID, and what happens if you don't write it?
It is a version number for the class: during deserialization the JVM compares the UID in the bytes with the current class's, and throws InvalidClassException if they don't match. If you don't write it, the JVM computes it from the class structure, and even a small change to the class makes old data unreadable.
26
Do you have to close the Stream returned by Files.lines()? Doesn't it finish after the terminal operation?
Yes, you do. A terminal operation makes the stream "used up", but it does not call close(). Files.lines holds an open file that is released only when the stream is closed, so you need try-with-resources.
27
What does this code print: why does length() differ from the byte count?
It prints 6 and 7. length() counts UTF-16 code units, which is 6 characters. In UTF-8, plain Latin letters take 1 byte, but the ʻ (U+02BB) character from the official Uzbek orthography takes 2 bytes. The number of characters and the number of bytes are not always equal.
28
The end of a file written with BufferedWriter sometimes goes missing. Why?
The last chunk is still in the buffer and never reached the disk: the writer was not closed or flushed. If the program exits with System.exit or just drops the writer, the buffer contents are lost.
29
A relative path like Path.of("data/input.txt") is resolved relative to which directory?
A relative path is resolved against the current directory the JVM was started from (the working directory, user.dir), not against where the class file or the jar is. That is why code that worked in the IDE can fail to find the file on the server.
30
Which options do you need to know when using Files.copy and Files.move?
By default, both throw FileAlreadyExistsException if the target file exists; to overwrite you need REPLACE_EXISTING. For move, ATOMIC_MOVE never leaves a half-moved file, and for copy, COPY_ATTRIBUTES also copies timestamps and permissions.
31
What are position, limit and capacity in an NIO ByteBuffer, and how does flip() change them?
capacity is the total size of the buffer, position is the next read/write location, and limit is the boundary you can't go past. flip() switches from write mode to read mode: limit = position, position = 0.
32
What is an NIO Channel, and how does it differ from the classic InputStream/OutputStream?
A Channel is two-way communication with a file or socket: you can both read from and write to the same object, and it works through a ByteBuffer. A stream is one-directional and blocking; a channel can be switched to non-blocking mode and used with a Selector.
33
How do you process a 10 GB log file with a 512 MB heap?
You don't load the file into memory at all; you stream it line by line: BufferedReader.readLine() or Files.lines inside try-with-resources. Memory holds only the current line and the result (for example, counters).
34
In Spring, what security mistakes can you make when saving a user-uploaded file to disk?
The most dangerous is path traversal: getOriginalFilename() can be ../../etc/cron.d/x. You need to generate the file name yourself, normalize() the path and check that it is inside the base directory, and limit the size and type.
35
What is the difference between ByteBuffer.allocate() and ByteBuffer.allocateDirect(), and when do you pick which?
allocate creates a buffer over a byte[] on the regular Java heap, while allocateDirect uses native memory outside the heap. With a direct buffer the OS IO needs no extra copy, but it is more expensive to create and the GC cleans it up late.
36
How do you write a large file download endpoint in Spring?
Don't load the file into memory as a byte[]; stream it into the response: return a Resource (FileSystemResource) or use StreamingResponseBody. Set Content-Disposition and Content-Length in the headers.
37
How do you create temporary files, and what do you do so they don't pile up on disk?
Files.createTempFile(prefix, suffix) creates a file with a unique name. Then you must delete it in a try-finally with Files.deleteIfExists. Don't rely on deleteOnExit(): it only works when the JVM shuts down normally and can leak memory on a long-running server.
38
Why is Java serialization hardly used today for exchanging data between services?
Java serialization is readable only by Java, very sensitive to class changes, slow and bulky. Most importantly, deserializing from an untrusted source can lead to remote code execution. JSON, Protobuf and Avro are used instead.
39
What is the difference between Externalizable and Serializable?
With Serializable the JVM writes all the fields itself using reflection. With Externalizable you fully control what is written and how in the writeExternal and readExternal methods; the class must have a public no-argument constructor.
40
How do you watch for a new file appearing in a directory? How does WatchService work?
You register a directory with the WatchService and it gives you create, modify and delete events. It watches only one directory (not recursively), can lose events, and does not guarantee that a file has been written completely.
41
How does an NIO Selector work, and how does a single thread serve thousands of connections?
All the SocketChannels are put into non-blocking mode and registered with one Selector. select() asks the OS (epoll on Linux) which channels are ready to read or write, and the thread works only with the ready ones, so it never gets stuck waiting on one slow client.
42
What is a memory-mapped file (MappedByteBuffer), when is it useful, and what are the risks?
FileChannel.map attaches the file to the process's virtual memory: reading from the buffer becomes reading straight from the OS page cache, with no system call and no copy. It is very fast for random access to big files, but unmapping is not under your control, and if the file shrinks, the process can crash.
43
How does FileChannel.transferTo achieve "zero-copy", and where does it help?
In an ordinary copy, data travels disk → kernel → user-space buffer → kernel → socket. On Linux transferTo uses sendfile to move the data inside the kernel straight to the socket: no copy into user space, fewer context switches.
44
"Too many open files" showed up on prod. How do you investigate and fix it?
First separate the cause: a real leak (the descriptor count grows steadily) or the limit simply being small (it climbs under load and then falls). With lsof//proc/<pid>/fd you see what is open, you fix a leak in the code, and you raise the limit through ulimit -n or the systemd/container settings.
45
Write a file so that even if the process crashes in the middle of writing, a reader never sees a half-written file.
Write the new content to a temporary file in the same directory, push it to disk with force(true), then swap it into the real name with Files.move(..., ATOMIC_MOVE). A rename is atomic: the reader sees either the old file or the new one, complete.
46
How does the Java deserialization vulnerability work, and how does ObjectInputFilter protect against it?
readObject creates any serializable class named in the bytes and runs its readObject/readResolve code. An attacker builds a chain out of "gadget" classes on the classpath to execute commands. ObjectInputFilter (Java 9+) restricts up front which classes, how much depth and how much size are allowed.
47
Text comes out garbled in a file from an external system. How do you pin down the encoding problem?
First look at the bytes themselves (xxd, hexdump): that tells you the real encoding. Then look along the chain for where the corruption happens: reading, inside Java, the DB connection, the HTTP response. To stop silent replacement, you can use CharsetDecoder in REPORT mode.
48
Two processes want to write to the same file. How does FileLock solve this, and what are its limitations?
FileChannel.lock() takes an OS-level lock; another process can't get it and waits (tryLock returns null immediately). But the lock is usually advisory: a program that doesn't check the lock can still write to the file. And it does not work between threads inside one JVM.
49
This code was supposed to copy a file, but the result file is empty. Where is the bug?
buf.flip() is not called after reading from the channel. position stays at the end of the buffer and limit at capacity, so write sees "nothing to write". On top of that, clear() or compact() is also needed after writing.
50
How did Java 21 virtual threads change the way we look at blocking IO? Do we still need NIO and the reactive approach?
When a virtual thread waits in blocking IO it frees the carrier thread, so plain InputStream/JDBC code can hold tens of thousands of simultaneous connections. But blocking inside synchronized (before Java 24) and file IO can still tie up a carrier, and reactive still makes sense for backpressure and streaming.
51
Reading a file written with `GZIPOutputStream` throws `EOFException: Unexpected end of ZLIB input stream`. What could be the cause?
A gzip stream writes a trailer (CRC32 and the original length) at the end, and it only comes out on finish() or close(). If the stream is not closed, or the result is taken before that, the file is left incomplete and the reader decides it is corrupt.
52
What is a suppressed exception in try-with-resources, and where can it get lost?
If an exception is thrown inside the try block and then close() throws one too, the main error is kept and the one from close() is attached to it with addSuppressed. You get it with getSuppressed().
53
What are the traps of writing a string with `DataOutputStream.writeUTF`?
It writes not plain UTF-8 but "modified UTF-8", and puts a 2-byte length in front. If the encoded string exceeds 65535 bytes you get UTFDataFormatException, and a non-Java reader sees \u0000 and emoji differently.
54
Can several threads use a single `FileChannel` together? What happens to the channel position?
Yes, FileChannel is thread-safe. But read(buf)/write(buf), which rely on the current position, wait for each other, and the position is shared by everyone. For parallel work use the positional read(buf, pos)/write(buf, pos), with each thread having its own buffer.
55
If you keep sending one modified object over a long-lived `ObjectOutputStream`, why does the other side see the old value, and why does memory keep growing?
ObjectOutputStream remembers every object it writes in a handle table and next time sends only a reference. The change doesn't go out, and the table isn't cleared until the stream is closed. The fix is reset() or writeUnshared().
56
Why is reading an `InputStream` from outside with `readAllBytes()` dangerous, and what do you do instead?
readAllBytes gathers everything into memory until the stream ends, with no limit. A large file or a deliberately endless stream fills the heap. You set the limit yourself: read with readNBytes(limit + 1) and reject if it is exceeded.
57
You need to walk a directory with hundreds of thousands of files. Which do you pick: `Files.list`, `Files.walk` or `DirectoryStream`?
For a single level, DirectoryStream or Files.list: both are lazy. For recursive traversal, Files.walk, or Files.walkFileTree when you need filtering. File.listFiles() loads everything into an array at once.
58
How do you delete a directory with everything in it, and what mistakes come up here?
Files.delete only deletes an empty directory. For recursive deletion you delete the result of Files.walk in reverse order, or use Files.walkFileTree and delete the directory in postVisitDirectory. It matters not to follow symlinks and to choose whether to stop on an error.
59
A number read with `getInt()` from a binary file written by another system comes out strangely large. What could be going on?
ByteBuffer is big-endian by default. If the file was written in little-endian (C/C++ on x86, .NET, many binary formats), the bytes are read in reverse. You need to set buf.order(ByteOrder.LITTLE_ENDIAN); DataInputStream reads big-endian only.
60
A file name uploaded from macOS doesn't `equals` the name in the database, even though they look the same on screen. What is the cause, and how do you fix it?
Unicode can write one letter in two ways: a precomposed character (NFC) or a base letter + a combining mark (NFD). macOS, and archives created there, often give file names in NFD. Before comparing, you bring both to one form with Normalizer.normalize(s, Normalizer.Form.NFC).
61
When reading UTF-8 data in blocks, sometimes `�` appears instead of letters. What is the cause, and how do you fix it?
A UTF-8 character takes 1 to 4 bytes. If you do new String(chunk, UTF_8) on each block separately, half a character is left at the block boundary and the decoder replaces it with U+FFFD. You need a decoder that keeps state.
62
How do you check whether two `Path`s point to the same file? Why isn't `equals` enough?
Path.equals only compares the path text: data/../b.txt, ./b.txt and an absolute path are not equal. normalize() and toAbsolutePath() clean up the text, but symlinks are resolved only by toRealPath() or Files.isSameFile, which go to the disk.
63
What values do `transient` fields have after deserialization, and how do you restore them?
They get default values: null, 0, false. Neither the constructor nor the field initializer is called. To restore them, you recompute the value in readObject after defaultReadObject().
64
Why does a Serializable singleton turn into a second instance after deserialization, and how do you stop that?
Deserialization creates a new object every time, bypassing even the private constructor. With readResolve() you return the existing instance instead of the new object. The most reliable way is to make the singleton an enum.
65
How do `record` classes differ from ordinary classes in Java serialization?
A record is created through its canonical constructor during deserialization, so the constructor's checks run and a stream can't bypass the invariant. Custom methods like readObject/writeObject are ignored, and serialVersionUID defaults to 0L and is not required to match.
66
You need to read one record from the middle of a multi-gigabyte file. How do you do it, and why is a stream awkward here?
With FileChannel (or the old RandomAccessFile) you do a positional read from an exact offset: channel.read(buf, offset). An InputStream only moves sequentially, and skip has no guarantees and is slow in many cases.
67
How do you compute the SHA-256 hash of a multi-gigabyte file without filling memory?
You read the file in chunks and feed each chunk to MessageDigest.update, or wrap the stream in a DigestInputStream and read to the end. Memory holds only the buffer and the digest state. You turn the result into text with HexFormat (Java 17).
68
One piece of code writes data to an `OutputStream`, while another API expects it as an `InputStream`. How do you connect them without an intermediate file and without gathering everything in memory?
With a PipedOutputStream/PipedInputStream pair: the writer runs in one thread and the reader in another, with a small circular buffer between them. If you use both in a single thread you get a deadlock, and the writer's error has to be delivered to the reader separately.
69
When writing a secret key or token file to disk, how do you set the permissions correctly?
Creating the file first and then calling setPosixFilePermissions leaves it open to others in between. The right way is to give the permissions at creation time: Files.createFile(path, PosixFilePermissions.asFileAttribute(...)) or an attribute on newByteChannel. The umask affects the result too.
70
To read an archive, which do you pick, `ZipFile` or `ZipInputStream`, and what do you watch out for when extracting a user-uploaded zip?
ZipFile reads a file on disk through the central directory at its end, so you go straight to the entry you need. ZipInputStream reads the stream sequentially from the start, so you can work without saving the file. For an uploaded archive, you limit names, size and the number of entries against zip slip and zip bombs.
71
A service opens and writes its own log file. After logrotate moves the file, the new log stays empty while the disk keeps filling up. Why does this happen, and how do you solve it?
Java writes to the inode through an open descriptor, not to the file name. After mv it keeps writing to the old, rotated file; if that gets deleted, it is deleted but still open, and the space isn't freed. The solutions: leave rotation to the logger itself, use copytruncate, or have a reopen mechanism.
72
While writing a large response to a non-blocking channel, `write()` wrote only part of the bytes. How do you handle this correctly?
You keep the remaining bytes in the connection's outgoing queue and turn on OP_WRITE. When the channel is ready to write again, you continue, and when the queue is empty you turn OP_WRITE off, otherwise the selector spins idle.
73
Why do systems that write to disk sequentially (append), like Kafka, run much faster than ones that update data in place? How do you use this idea in your own service design?
Sequential IO is where both the disk and the OS work best: writing in large blocks, read-ahead, reads from the page cache, no seeks on HDD, low write amplification on SSD. In a design this means an append-only log, batched writes, a small index and compacting old data later.
74
`write()` returned successfully. Does that mean the data was written to disk? When do you need `force()` and `fsync`?
No. write normally writes only to the OS page cache; if the power goes out, the data can be lost. FileChannel.force(true) (or FileDescriptor.sync()) asks the kernel to push it to the device, and it is an expensive operation.
75
A mobile app uploads large files over an unreliable network. How do you design resumable uploads on the server side, continuing from the point of interruption?
First you open an upload session (ID, expected size, hash). The client sends the file in chunks with an offset; the server writes each chunk positionally and stores the confirmed offset. If the connection drops, the client asks for the offset and continues from there. At the end you verify the overall hash and put the file in place with an atomic move.
76
How does blocking file IO work with virtual threads? Is it different from socket IO?
It is different. With socket IO the virtual thread detaches from the carrier and the wait happens in the kernel through epoll. OSes usually don't make file IO non-blocking, so the virtual thread ties up the carrier; the JDK compensates by temporarily growing the carrier pool.
77
You need to process a 20 GB CSV file and load it into the database. How do you control memory and time?
You never load the whole file into memory: read line by line with a buffered reader and write in batches after parsing. For speed, you parallelize the parsing and the DB writes through a bounded queue, and for restarts you save an offset/checkpoint.
78
You launched an external command with `ProcessBuilder` and `waitFor()` never returns. What happened from an IO standpoint?
The child process writes to stdout or stderr and you don't read it. Once the OS pipe buffer (usually 64 KB on Linux) fills up, the process blocks in write and never finishes, while you wait for it to finish. You need to read the streams, redirect them to a file, or discard them.
79
When downloading a large file with `java.net.http.HttpClient`, how do you write the response to disk rather than memory, and how do you resume an interrupted download?
BodyHandlers.ofFile(path) or ofInputStream() streams the response to disk; ofString/ofByteArray collect everything on the heap. To resume, you send Range: bytes=N-, check that 206 Partial Content came back, and write to the file with APPEND.
80
Does `AsynchronousFileChannel` really do asynchronous IO? When does it make sense to use it?
The API is asynchronous, but on Linux the JDK runs it in an internal thread pool with plain blocking pread/pwrite: kernel-level async file IO is not used. On Windows there is real overlapped IO. In most cases you get the same result from a plain FileChannel with your own executor.
81
A service runs on three instances and users upload files. Do you store the files on local disk or in object storage? How do you justify the decision?
In a multi-instance service, local disk means state: knowing which pod holds a file, backups and migration all become problems. So I usually take object storage (S3 or a compatible one) + metadata in the database; local disk stays only in a small single-server system or as a temporary buffer.
82
You need to upload and serve gigabyte-sized files through a Spring Boot service, and the heap is 512 MB. How do you design the whole path?
The bytes must never land in memory in full: stream the multipart to disk or straight to storage, and serve the response through StreamingResponseBody/Resource. Best of all, don't pass large files through the service at all; send the client to the storage with a presigned URL.
83
You have to write an append-only journal (WAL) file for your service yourself. How do you design the format and the write order so that it recovers correctly after a crash?
You write each record as length + checksum + data; on recovery you drop the last incomplete or corrupt record. You batch fsync with group commit, split the file into segments, and delete old segments after a checkpoint.
84
For a new high-load gateway service, which model do you choose: Netty (event loop) or plain blocking code with virtual threads?
On Java 21+, virtual threads + blocking code are enough for many services and much simpler for the team. Netty pays off when you need a huge number of long-lived connections, streaming protocols, minimal latency and precise control over memory.
85
How do you choose a serialization format for data exchanged between services and stored on disk for a long time: JSON, Protobuf, Avro or Java serialization?
I rule out Java native serialization immediately: it is unsafe, slow and tied to Java. Among the rest, the choice depends on schema evolution, readability, size and the ecosystem: JSON for external APIs, Protobuf for internal RPC, and for Kafka and a data lake often Avro + a schema registry.
86
Describe the full protocol for updating an important file on disk (say, a local state snapshot) so it survives a power loss.
Write the new content to a temporary file, fsync that file, swap it in with an atomic rename, then fsync the directory itself. At startup you clean up leftover .tmp files and verify the content with a checksum.
87
The server's disk filled up on prod. How should the service behave, and how do you design for it in advance?
A full disk is not one service's bug but the whole host's: logs, temp files and the DB WAL fail at the same time. You think about it ahead of time: a limit on everything that writes to disk, monitoring, and a clear behavior when the disk is full (reject writes, turn off readiness).
88
When the disk slowed down, the whole service's p99 latency shot up, even though requests barely touch files. How does this happen, and how do you prevent it?
Usually synchronous logging is to blame: every request writes a log, the appender writes to disk under a lock, and when the disk freezes, all threads line up on that lock. An async appender, a bounded queue and keeping disk IO off the request path are the main protection.
89
The service is crashing with `OutOfMemoryError: Direct buffer memory` while the heap is half empty. How do you investigate, and what limit policy do you set?
Direct buffers live outside the heap and are released only when their Java object is collected by the GC. With Native Memory Tracking and BufferPoolMXBean you see who is allocating and how much; then you set MaxDirectMemorySize explicitly and tune the libraries' pools.
90
A Java service on Kubernetes works with files a lot and gets OOMKilled from time to time, while the heap is well below the limit. How could file IO be related?
The container's memory accounting (cgroup) includes page cache and tmpfs. Writing large files increases dirty pages, and emptyDir with medium: Memory is straight RAM. Add mmap and direct buffers, and the process exceeds the limit even if the heap is small.
91
Several servers exchange files through a shared NFS directory. Where does Java IO code break in such an environment, and what do you propose?
NFS doesn't fully provide local disk semantics: attributes are cached, rename and locks work with delays and errors, WatchService doesn't see changes made on another machine, and IO hangs on an outage. Instead of file-based integration, I propose a queue or object storage.
92
The producer is fast, while the consumer (disk or network) is slow. How do you design backpressure in an IO pipeline?
Every buffer between stages has to be bounded, and what happens when it is full is chosen explicitly: wait (block), drop, or slow down the producer. An unbounded queue is not backpressure; it is a delayed OutOfMemoryError.
93
The company wants to build a self-hosted service that serves large video and archive files. What architecture decisions do you make at the IO level?
I take serving the bytes off the Java application and hand it to a layer built for it: a CDN, or a reverse proxy that uses sendfile. The Java service deals only with authorization, metadata and signed links; Range requests, caching and TLS live at the edge.
94
Services from different teams exchange text data, and from time to time Uzbek or Russian letters come out garbled. How do you establish an encoding policy at the organization level?
"UTF-8 everywhere, and explicitly declared at every boundary": one rule. You make it mandatory in the JVM settings, HTTP headers, the DB and file formats, and verify it with CI and contract tests. Exceptions (for example CSV for Excel) are written down clearly in the docs.
95
You need to design your own binary file format (for example for an index or an export). What do you build in from the start to make it readable for years and safe?
A magic byte sequence and a format version at the start of the file, explicit endianness, a length and checksum on every block, an extensible header (so unknown fields can be skipped), and an upper bound on every length when reading. Optionally, a footer/index at the end.
96
Users ask to download a report with millions of rows as CSV or Excel. How do you design this feature so it doesn't take the service down?
I don't generate the report synchronously inside the HTTP request: an asynchronous job, reading from the DB as a stream with a cursor, writing the file to storage in chunks, and a download link when it is ready. For Excel you use a streaming writer (Apache POI SXSSF) and limit the number of concurrent exports.
97
The team brought a benchmark result saying "our new file library is 3 times faster". What mistakes show up in IO benchmarks, and what do you require before trusting the result?
Most of the lying in IO benchmarks comes from the page cache: the second read comes from RAM, not the disk. And on writes, measuring without fsync measures the kernel buffer. I require cold/warm cache states, file size relative to RAM, an fsync policy and a prod-like environment.
98
Your codebase has parts that work off-heap with `MappedByteBuffer`, `sun.misc.Unsafe` and direct buffers. Should you move to the Foreign Function & Memory API, and how do you plan it?
Yes, in the long term: the FFM API is final from Java 22, while the memory methods of Unsafe are being deprecated step by step and are headed for removal. MemorySegment and Arena give safer off-heap memory with no 2 GB limit and an explicit lifecycle. The migration: put the boundary behind an abstraction, measure, and go step by step.
99
This endpoint lets users download files from their own directories. Does it pass a security review? What layers of protection do you put in multi-tenant file storage?
It does not: by passing ../../other-tenant/secret.pdf or an absolute path as name, you can get another customer's file. You need to normalize the path and check that it stays inside the root, but the main protection is not using user-supplied names as a path at all.
100
Java has no timeout for file operations. When a disk or network file system freezes, how do you protect the rest of the service?
You run blocking file IO not on request threads but in a separate bounded executor, and wait for the result on a Future with a timeout. A hung thread can't be stopped, so a pool bound and a circuit breaker limit the damage; the health check also covers the IO path.
Sign up — studied questions get marked and your progress is saved.