BackendBench
Coffee
Spot the Bug #30

The ZIP archive that stays mapped

A hard Java puzzle in the resource leaks family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

hardResource leaksbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

ZipFile keeps the archive open and uses native memory until close is called. The method returns the size and drops the reference, but the file handle stays open until the finalizer runs, which may never happen in time. On Windows the file cannot even be deleted.

The fix

try (ZipFile zip = new ZipFile(path)) { return zip.size(); }

How to avoid it next time

ZipFile, JarFile, Socket, HttpClient responses, and database objects are all closeable. Wrap each in try-with-resources.

Want the background? Read ZIP and GZIP compression in the Java concepts library.

About resource leaks

Files, streams, sockets, connections and statements hold operating system handles that the garbage collector will not release promptly. A leak often shows up only in production after hours of load as too many open files or an exhausted connection pool.

In code review: Every constructor of a closeable type should sit in a try-with-resources header. Check the exceptional path as well as the normal one.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #29#31 โ†’

Frequently asked questions

What is the bug in "The ZIP archive that stays mapped"?

ZipFile keeps the archive open and uses native memory until close is called. The method returns the size and drops the reference, but the file handle stays open until the finalizer runs, which may never happen in time. On Windows the file cannot even be deleted. The faulty line is line 7: return zip.size();

How do I fix it?

Replace it with: try (ZipFile zip = new ZipFile(path)) { return zip.size(); }. ZipFile, JarFile, Socket, HttpClient responses, and database objects are all closeable. Wrap each in try-with-resources.

How do I catch resource leaks in code review?

Every constructor of a closeable type should sit in a try-with-resources header. Check the exceptional path as well as the normal one.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need