Quick revision
The short answer
close() must release the resource exactly once and do nothing on later calls, which Closeable requires and AutoCloseable strongly recommends, and if close may be called from several threads, an AtomicBoolean with compareAndSet makes that once-only check safe. We declare close() with a narrow exception, or none, so callers need little handling, make every other method throw IllegalStateException after close, and register a java.lang.ref.Cleaner action as a safety net that releases the resource if the object becomes unreachable and logs that the caller forgot to close it.
What to remember
In this answer, we designed an AutoCloseable class step by step. close() releases the resource once and ignores later calls, an AtomicBoolean with compareAndSet makes that safe across threads, the close() signature declares a narrow exception or none, and methods called after close throw IllegalStateException. A Cleaner registered with a separate state object acts as a safety net that frees the resource and logs a warning if a caller forgets to close, while try-with-resources remains the expected way to use the class.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
close() must release the resource exactly once and do nothing on later calls, which Closeable requires and AutoCloseable strongly recommends, and if close may be called from several threads, an AtomicBoolean with compareAndSet makes that once-only check safe. We declare close() with a narrow exception, or none, so callers need little handling, make every other method throw IllegalStateException after close, and register a java.lang.ref.Cleaner action as a safety net that releases the resource if the object becomes unreachable and logs that the caller forgot to close it.
Why this question is asked
Classes that hold a native handle, a socket or a pooled connection are where resource leaks come from. Callers forget to close, close twice, or close from one thread while another is still using the object. A well-designed AutoCloseable makes all of those cases safe or at least loud. Interviewers ask this design question to see whether we know the contracts, can handle concurrency without overdoing it, and know the modern replacement for finalize(). In this answer, we will build a small NativeBuffer class step by step: idempotent close, thread safety, the exception signature, the closed state, and finally a Cleaner safety net.
1The Class We Are Building
Imagine a class that wraps a native buffer, memory allocated outside the Java heap through a library call, identified by a long handle. If nobody frees it, the memory is lost until the process exits, and the garbage collector does not know about it. The same design applies to a socket, a file descriptor or a connection borrowed from a pool.
The naive close() frees the handle every time it is called. A second call would free memory that may already have been reused, which in native code can crash the process.
2Make close() Idempotent
Idempotent means calling close() twice has the same effect as calling it once. java.io.Closeable requires it: closing a closed stream has no effect. AutoCloseable only strongly encourages it, but there is no good reason not to, because callers often close twice by accident, for example a wrapper closing its inner resource and try-with-resources closing it again.
This is enough for a class used by one thread at a time. It is not enough when two threads may call close() at once: both could read closed as false and both would free the handle.
3Make It Safe Across Threads
When close() may come from more than one thread, for example a request thread finishing and a shutdown hook running together, we replace the flag with an AtomicBoolean and use compareAndSet. Only one caller can change it from false to true, so only one caller frees the handle.
5 messages in order. Play them, or step through them one at a time.
Notice what this does not solve: a write that has already passed the check while another thread closes the buffer. If the class must support concurrent use and close, we need a lock or a read-write lock around use and close, or a reference count. Often the better design is to document that the object is not thread safe for use, and only make close() safe to call more than once.
4Choose a Narrow close() Signature
AutoCloseable.close() is declared to throw Exception, but an implementing class may declare fewer exceptions, and callers using our concrete type see our declaration. If we declare close() with no checked exception, try-with-resources around a NativeBuffer needs no catch block at all. If closing can genuinely fail in a way callers should know about, we declare the narrowest type, such as IOException, or throw an unchecked exception.
Close should also avoid throwing for things the caller cannot fix. Logging a failed release and continuing is usually better than throwing from close, since close often runs while another exception is already propagating, where it becomes a suppressed exception.
5A Cleaner as a Safety Net
Even with all of this, some caller will forget to close. Since Java 9, java.lang.ref.Cleaner lets us register an action that runs after the object becomes unreachable, replacing the deprecated finalize(). The action must not refer to the NativeBuffer itself, or the object would never become unreachable, so the state it needs lives in a separate static class.
- Caller closes the buffer?Yesclose() marks closedByCaller, calls clean()NoObject becomes unreachable
- Already cleaned?YesDo nothingNoRun State.run()
- Closed by caller?YesFree the handle quietlyNoLog a leak warning, then free
3 steps in order. Play them, or step through them one at a time.
Cleanable.clean() runs the action at most once, whether it is triggered by close() or by the garbage collector, so the native memory is freed exactly once on either path. The warning tells us which callers leak, so we can fix them. But the Cleaner is only a safety net: it runs at an unpredictable time, maybe never if memory is plentiful, so callers must still use try-with-resources.
6Follow-up questions
Why not use finalize()?
finalize() is deprecated for removal. It runs at unpredictable times, can resurrect objects, slows garbage collection, and errors inside it are ignored. Cleaner avoids resurrection by design, because its action cannot reach the object, and it can be triggered explicitly from close().
Should close() wait for in-progress operations?
It depends on the resource. For a connection-like object, a common design is that close() marks the object closed so new calls fail, then waits briefly for in-flight calls using a lock or counter. For a simple buffer used by one thread, documenting single-thread use is clearer.
How do we test the Cleaner path?
Create the object without closing it, drop the reference, and call System.gc() in a loop while waiting for the leak warning or a counter. It is not deterministic, so such tests should be few and tolerant, while normal tests cover close() directly.
7Conclusion
In this answer, we designed an AutoCloseable class step by step. close() releases the resource once and ignores later calls, an AtomicBoolean with compareAndSet makes that safe across threads, the close() signature declares a narrow exception or none, and methods called after close throw IllegalStateException. A Cleaner registered with a separate state object acts as a safety net that frees the resource and logs a warning if a caller forgets to close, while try-with-resources remains the expected way to use the class.
Open with
I would start from the contract: close releases the resource exactly once and later calls do nothing. Closeable requires that and AutoCloseable recommends it, and double closes happen all the time, for example when a wrapper and try-with-resources both close.
Then, if they want more
If close can be called from several threads, I use an AtomicBoolean and compareAndSet(false, true), so only the first caller actually releases the handle. Every other method checks the flag and throws IllegalStateException if the object is closed, so use after close fails clearly instead of touching freed memory.
If the object must support concurrent use and close at the same time, a flag is not enough and I would need a lock or reference count, but usually I document it as not thread safe for use and only make close safe.
For the signature, I override close with a narrow exception or none at all, so callers using try-with-resources with my type need no catch; AutoCloseable's own close throws Exception, which is painful. Finally, for callers who forget, I register a Cleaner action.
The state it needs, the handle, lives in a separate static class so it does not reference the object itself. close calls cleanable.clean, which runs at most once, and if the Cleaner runs it after GC instead, it logs a leak warning and frees the handle. It is a safety net, not a replacement for closing.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You design a class that holds a native resource or a connection. How do you implement...": https://scrivio-interview-library.netlify.app/java/exceptions/c2debf8268/