3 ms·
Secure your code against the finalizer vulnerability
- asymptotic 15y agoFWIW, from Bloch's "Effective Java" (2nd Edition): "Finalizers are unpredictable, often dangerous, and generally unnecessary. Their use can cause erratic behavior, poor performance, and portability problems. Finalizers have a few valid uses, which we'll cover later in this item, but as a rule of thumb, you should avoid finalizers... One of the shortcomings of finalizers is that there is no guarantee they'll be executed promptly. It can take an arbitrarily long time between the time that an object becomes unreachable and the time that its finalizer is executed. This means that you should never do anything time-critical in a finalizers. For example, it is a grave error to depend on a finalizer to close files, because open file descriptors are a limited resource... Not only does the language specification provide no guarantee that finalizers will get executed promptly; it provides no guarantee that they'll get executed at all. It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longers reachable. As a consequence, you should never depend on a finalizer to update critical persistent state... Oh, and one more thing: there is a severe performance penalty for using finalizers." Why would anyone ever consider using a finalizer?
- wladimir 15y agoWell, to stay with the example of file handles, one might forget to explicitly close the file. The finalizer would then act as a safety net and close the file as soon as the object is garbage collected. But indeed, it is a very bad idea to rely on that. Even in languages that have reference-counting garbage collection semantics (such as Python) it is recommended to explicitly close files, as someone might still have a reference around.