Resource management (computing): Difference between revisions

Content deleted Content added
Object-oriented programming: elab, integrate RAII (make it less RAII-focused), and contrast owning vs. viewing
Complex relationships: examples, fix File
Line 90:
Implementation-wise, in object composition, if using the dispose pattern, the owning object thus will also have a <code>dispose</code> method, which in turn calls the <code>dispose</code> methods of owned objects that must be disposed; in RAII this is handled automatically (so long as owned objects are themselves automatically destroyed: in C++ if they are a value or a <code>unique_ptr</code>, but not a raw pointer: see [[pointer ownership]]). In object aggregation, nothing needs to be done by the viewing object, as it is not responsible for the resource.
 
Both are commonly found. For example, in Java, <code>[https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html#close-- Reader#close()]</code> closes the underlying stream, and these can be chained. For example, a <code>[https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html BufferedReader]</code> may contain a <code>[https://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html InputStreamReader]</code>, which in turn contains a <code>[https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html FileInputStream]</code>, which in turn contains a <code>[https://docs.oracle.com/javase/8/docs/api/java/io/File.html File]</code>, and calling <code>close</code> on the <code>BufferedReader</code> in turn closes the <code>InputStreamReader</code>, which in turn closes the <code>FileInputStream</code>, which in turn closes the <code>File</code>, which in turn releases the system file resource.
 
<source lang="Java">
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
// Use reader.
}
// reader is closed when the try-with-resources block is exited, which closes each of the contained objects in sequence.
</source>
 
By contrast, in Python, a [https://docs.python.org/2/library/csv.html#csv.reader csv.reader] does not own the <code>file</code> that it is reading, so there is no need (and it is not possible) to close the reader, and instead the <code>file</code> itself must be closed.<ref>[http://stackoverflow.com/questions/3216954/python-no-csv-close Python: No csv.close()?]</ref>
 
<source lang="Python">
with open(filename) as f:
r = csv.reader(f)
# Use r.
# f is closed when the with-statement is exited, and can no longer be used.
# Nothing is done to r, but the underlying f is closed, so r cannot be used either.
</source>
 
In case of a more complicated [[object graph]], such as multiple objects sharing a resource, or cycles between objects that hold resources, proper resource management can be quite complicated, and exactly the same issues arise as in object finalization (via destructors or finalizers).