Search code examples
java.netgarbage-collectionfinalizer

Java equivalent of GC.SuppressFinalize


Does Java have an equivalent of .Net's GC.SuppressFinalize?

In .Net, SuppressFinalize is used in the dispose pattern to avoid the relatively high performance cost of finalization as long as the object is explicitly disposed. Similar costs apply to Java, but it doesn't seem to have SuppressFinalize.

I know that generally it's better to simply avoid finalizers altogether, but I don't think I can avoid them for my particular use case (a cancel token where you can add handlers that run only if another token isn't cancelled first, so a token becoming immortal due to its source being collected must result in entries being removed from linked tokens lest they accumulate garbage entries without bound).

Is there an equivalent of SuppressFinalize in Java? If not, can it be approximated by using the available tools (e.g. ReferenceQueue)?


Solution

  • There is no native "GC.SuppressFinalize" method for Java. But IDiposable pattern will be useful for you to address this.

    You can Manually dispose of an item when you know it is no longer needed or Be able to run clean up code to safely bring down connections, close files, etc.Also you will be able to use finalizer to catch situation where it is not known when an object should be cleaned up.