Scala

Scala

Made by DeepSource

finalizers should not be defined explicitly SC-R1046

Bug risk
Major

finalizers may contain the required logic necessary for performing clean-up actions such as freeing up of resources. However, they're triggered by the JVM when and as deemed necessary. This means that your logic may be executed at a time when the resources that are to be freed are no longer available. Additionally, once invoked, finalizations cannot be interrupted and do not guarantee any specific ordering. It is therefore recommended that you use interfaces such as AutoCloseable to perform the required clean-up actions.

Bad practice

class C {
  override def finalize(): Unit = {
    // clean up logic
  }
}

Recommended

class C extends AutoCloseable {
  override def close(): Unit = {
    // clean up logic
  }
}