O'Reilly logo

Shared Source CLI Essentials by Ted Neward, Geoff Shilling, David Stutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Finalization

There is an obvious problem with using automatic memory management in conjunction with pointers to unmanaged resources: when components hold references to nonmanaged resources that need to be explicitly disposed of, it is necessary to make sure that the resource is disposed of before the object is collected. The CLI supports a concept called finalization to solve this problem. Finalizable objects are placed on a special weak reference list when created. The collector monitors this list and when all strong references to a finalizable object are released, moves the reference from the weak list to the finalization queue, which continues to keep the object alive. (We saw the finalization queue appear in numerous scan examples earlier in this chapter.) The finalization thread will go though the list of objects in a lazy fashion and call the finalization method on each object. If an object does not become reachable again as a result of being finalized (remember, arbitrary code is being run within the finalization method that can reestablish references!), the finalization reference will be released, and the object will be collected in a normal fashion.

Note

One interesting issue for programmers is that garbage collection happens at unpredictable times, depending on the algorithm and the load. Because of this, it is sometimes desirable to go beyond finalization and revert to an old-fashioned disposal pattern, in which programmers are required to explicitly “close” resources ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required