Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

Before a JDK upgrade you want to know whether any of your services or their dependencies still rely on finalization. How do you find out and handle it?

We find out in two ways at once: by testing the services with finalization switched off, using --finalization=disabled on JDK 18 or later, and by looking for classes that actually have finalizers, using JFR's jdk.FinalizerStatistics event at run time and a scan of our code and dependency jars at build time. Each class we find is either our own code, which we rewrite with close() and Cleaner, or a dependency, which we upgrade or replace, so that a future JDK without finalization holds no surprises.

Why this question is asked

Finalization is deprecated for removal, so at some point a JDK release will stop calling finalize() altogether. If one of our services, or one of the hundred jars it depends on, still relies on a finalizer to close a file or free native memory, that upgrade will turn into a slow leak in production. Interviewers ask this to see whether we can turn a vague risk into a concrete, measurable plan. In this answer, we will recap why a hidden finalizer is dangerous, then walk through how to find them at run time and in the build, how to handle each one we find, and how to keep the problem from coming back.

1A Quick Recap: Why Hidden Finalizers Matter

A finalizer is a finalize() method that the garbage collector calls some time after an object becomes unreachable. Older libraries used it to release resources the collector does not manage, such as file descriptors, sockets or off-heap memory, for callers who forgot to close them. JEP 421 in JDK 18 deprecated the mechanism for removal.

The danger is that a finalizer can quietly hide a bug in our own code. Suppose a service forgets to close a stream in some error path. Today the stream's finalizer eventually closes it, so the bug never shows. On a JDK without finalization, the descriptors pile up until the process hits its limit, often 1024 or 65536 open files, and requests start failing with Too many open files. So the question is not only whether finalizers exist, but whether anything is leaning on them.

2Run Tests and Staging With Finalization Disabled

JDK 18 added a switch that simulates the future: --finalization=disabled. With it, objects are still collected, but no finalize() method is ever called. This is the most direct test we have, because it shows the behaviour of the service exactly as it will be once finalization is removed.

Text
# test suite
./mvnw verify -DargLine="--finalization=disabled"
# staging, next to an identical instance with the default setting
JAVA_TOOL_OPTIONS="--finalization=disabled" java -jar orders-service.jar
# watch the resources a finalizer would have released
ls /proc/$(pgrep -f orders-service)/fd | wc -l # open descriptors: 312, then 340, then 395 ...
jcmd $(pgrep -f orders-service) VM.native_memory summary # needs -XX:NativeMemoryTracking=summary

Functional tests rarely catch this kind of leak, because a test run is short and opens few resources. So we run a staging instance under real or replayed load for a day, side by side with an instance on the default setting, and compare open file descriptors, native memory and thread counts. If the disabled instance climbs steadily while the other stays flat, something depended on a finalizer, and the next steps tell us what.

3Ask the Running JVM Which Classes Have Finalizers

Recent JDKs record finalizer statistics in Java Flight Recorder, the low-overhead event recorder built into the JVM. The jdk.FinalizerStatistics event, added around JDK 18 (check your version), lists each class that has a finalizer, how many of its objects are currently registered, and how many finalizers have run. That turns the question into a list of class names.

Shell
jcmd <pid> JFR.start name=fin duration=30m filename=fin.jfr
jfr print --events jdk.FinalizerStatistics fin.jfr
# finalizableClass = com.legacy.ftp.FtpConnection objects = 1840 totalFinalizersRun = 22710
# finalizableClass = org.oldjdbc.PooledStatement objects = 96 totalFinalizersRun = 4031
jcmd <pid> GC.finalizer_info # a quick snapshot of what is waiting in the finalizer queue
Step throughFinding and fixing finalizer dependencies
  1. Run with --finalization=disabledtests, then a day of staging load
  2. Record jdk.FinalizerStatisticswhich classes have finalizers, how often they run
  3. Scan our code and dependency jarsclasses that override finalize()
  4. Is the class in our own code?
    YesRewrite with close() and CleanerNoUpgrade or replace the dependency
  5. Fix the callers that forgot to closetry-with-resources
  6. Add a build checkfail on new finalize() overrides

6 steps in order. Play them, or step through them one at a time.

Run-time evidence and a static scan together give the full list.

Notice that a class with a high totalFinalizersRun is the interesting one. A class with a finalizer that never runs is harmless today, but one whose finalizer runs thousands of times an hour is cleaning up after callers who did not close it, and that is exactly the leak we would get after the upgrade.

4Scan Our Code and Dependencies in the Build

Run-time data only shows the code paths that staging exercised. To catch the rest, we scan the bytecode. Two tools from the JDK help. The compiler, with -Xlint:removal, warns on every class that overrides a method deprecated for removal, which covers our own source. For compiled jars, jdeprscan reports uses of deprecated APIs, including overrides of Object.finalize(), across the whole dependency set (check its output format for your JDK).

Shell
javac -Xlint:removal ... # warning: [removal] finalize() in Object has been deprecated
jdeprscan --for-removal --class-path libs/* app.jar
# or a small scan of every jar for a method named finalize with descriptor ()V
for j in libs/*.jar; do
unzip -Z1 "$j" '*.class' | while read c; do
unzip -p "$j" "$c" > /tmp/c.class
javap -p /tmp/c.class | grep -q 'void finalize()' && echo "$j: $c"
done
done

The result is usually short. Typical hits are old JDBC drivers, old FTP or SSH clients, image and compression libraries with native code, and our own resource wrappers written years ago. Each one goes on a list with its owner and its fix.

5Handle Each Class We Found

For our own classes, the fix has two parts. First, the class implements AutoCloseable and its callers use try-with-resources, so the resource is released at the end of the block. Second, if the class is handed out to code we do not control, we keep a safety net by registering a Cleaner, whose action holds only the raw resource and never a reference to the object itself. Then we delete finalize().

For dependencies, we first check whether a newer version already dropped its finalizer; many did when JDK 18 was released. If not, we look for a maintained replacement. If neither exists, we make sure our own code closes every instance explicitly, which is what we should do anyway, and we confirm it with the disabled-finalization run. The finalizer then becomes dead code rather than a dependency.

6Plan for JDKs Without Finalization

Finally, we make the result stick. We add a build check that fails when a new class overrides finalize(), keep one CI job running the test suite with --finalization=disabled, and add the open-descriptor and native-memory graphs to the service dashboard with an alert on steady growth. When a future JDK removes finalization, the upgrade then changes nothing, because we have already been running as if it were gone.

7Follow-up questions

Is --finalization=disabled safe to use in production?

Yes, once staging has shown that resource usage stays flat with it. Some teams roll it out to production early, one service at a time, so the eventual JDK change is a non-event. If a leak appears, removing the flag restores the old behaviour immediately.

Why not just keep the dependency and hope the JDK keeps finalization?

Because the deprecation is for removal, the timeline is out of our hands, and the failure mode is a slow leak that appears days after the upgrade rather than a clear startup error. Finding the dependency now, while we can test calmly, is far cheaper.

What if a third-party library both has a finalizer and offers no close() method?

Then the library is relying on the collector to free its resources, and it will leak once finalization is gone. We report it upstream, wrap it so we can free the resource ourselves if the library exposes any way to do so, and plan its replacement.

8Conclusion

In this answer, we turned the risk of hidden finalizers into a concrete plan. We run tests and a day of staging load with --finalization=disabled and watch file descriptors and native memory. We record JFR's jdk.FinalizerStatistics event to see which classes have finalizers and how often they run, and we scan our code and dependency jars for finalize() overrides. Our own classes move to AutoCloseable with try-with-resources and a Cleaner safety net, dependencies are upgraded or replaced, and a CI job and a build check keep us ready for a JDK where finalization no longer exists.

What to say in the interviewAbout 80 seconds aloud

Open with

I would attack it from both run time and build time. First, I run the test suite and a staging instance under realistic load with --finalization=disabled, which JDK 18 added, next to an identical instance on the default, and I compare open file descriptors, native memory and thread counts over a day.

Then, if they want more

If the disabled one grows steadily, something relies on a finalizer. To find what, I record a JFR session and look at the jdk.FinalizerStatistics event, which lists each class with a finalizer and how many times its finalizers ran; a class with thousands of runs is cleaning up after callers that forgot to close.

Because staging only covers some paths, I also scan our code with javac -Xlint:removal and the dependency jars with jdeprscan or a bytecode scan for finalize overrides. For our own classes I implement AutoCloseable, fix callers to use try-with-resources, and keep a Cleaner as a safety net.

For dependencies I upgrade, since many dropped finalizers around JDK 18, or replace them. Then I keep a CI job running with finalization disabled and a build check against new finalize methods, so a future JDK that removes finalization changes nothing for us.

About this answer

Last updated
12 November 2026
Versions it names
Java 18
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.
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 "Before a JDK upgrade you want to know whether any of your services or their dependencies...": https://scrivio-interview-library.netlify.app/java/object-contracts/37b53d9ee3/