BackendBench
Coffee
Spot the Bug #27

Closing the keyboard

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: 6

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

What is wrong

Closing a Scanner closes the underlying System.in. The first call works, and the second call fails with NoSuchElementException because standard input is already closed. try-with-resources is right for resources you open, not for ones you borrow.

The fix

private static final Scanner IN = new Scanner(System.in); // share one Scanner and do not close it

How to avoid it next time

Close only what you opened. Create one Scanner for System.in and keep it for the life of the program.

Want the background? Read try-with-resources 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โ† #26#28 โ†’

Frequently asked questions

What is the bug in "Closing the keyboard"?

Closing a Scanner closes the underlying System.in. The first call works, and the second call fails with NoSuchElementException because standard input is already closed. try-with-resources is right for resources you open, not for ones you borrow. The faulty line is line 6: try (Scanner in = new Scanner(System.in)) {

How do I fix it?

Replace it with: private static final Scanner IN = new Scanner(System.in); // share one Scanner and do not close it. Close only what you opened. Create one Scanner for System.in and keep it for the life of the program.

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