- Dispose pattern
-
"Dispose" redirects here. For other uses, see Disposal (disambiguation).
In computer programming, the dispose pattern is a design pattern which is used to handle resource cleanup in runtime environments that use automatic garbage collection. The fundamental problem that the dispose pattern aims to solve is that, because objects in a garbage-collected environment have finalizers rather than destructors, there is no guarantee that an object will be destroyed at any deterministic point in time—a guarantee that is necessary for some other resource management patterns, such as Resource Acquisition Is Initialization. The dispose pattern works around this by giving an object a method (usually called
Dispose()
or something similar) which frees any resources the object is holding onto. Unless the language offers an alternative, this method must be manually invoked by clients that use the object once they are finished with it.Examples
Fundamentally, the pattern looks like this from the caller's point-of-view:
// Acquire the resource. Resource resource = null; try { resource = getResource(); // Perform actions with the resource. ... } finally { if (resource != null) { // Free the resource. resource.Dispose(); } }
The
try...finally
construct is necessary for proper exception safety—if the code that uses the resource throws an exception, the resource will not be freed unless theDispose()
call is in afinally
block. Also, the check againstnull
is necessary if the object representing the resource is not directly instantiated, but rather is obtained from some other source that could returnnull
.To make this pattern less verbose, several languages have some kind of built-in support for it. For example, C# features the
using
statement, which automatically and safely calls theDispose()
method on an object that implements theIDisposable
interface:using (Resource resource = GetResource()) { // Perform actions with the resource. ... }
Python's
with
statement can be used to similar effect:with get_resource() as resource: # Perform actions with the resource. ...
See also
Categories:- Object-oriented programming
- Memory management
- Software design patterns
Wikimedia Foundation. 2010.