Resource management (computing)
≈ 10 min read
Names in other languages
No names in other languages are held for this entry yet.
Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.
In computer programming, resource management refers to techniques for managing resources (components with limited availability). Computer programs may manage their own resources by using features exposed by programming languages ( is a survey article contrasting different approaches), or may elect to manage them by a host – an operating system or virtual machine – or another program. Host-based management is known as resource tracking, and consists of cleaning up resource leaks: terminating access to resources that have been acquired but not released after use. This is known as reclaiming resources, and is analogous to garbage collection for memory. On many systems, the operating system reclaims resources after the process makes the exit system call.
In computer programming, resource management refers to techniques for managing resources (components with limited availability). Computer programs may manage their own resources by using features exposed by programming languages ( is a survey article contrasting different approaches), or may elect to manage them by a host – an operating system or virtual machine – or another program. Host-based management is known as resource tracking, and consists of cleaning up resource leaks: terminating access to resources that have been acquired but not released after use. This is known as reclaiming resources, and is analogous to garbage collection for memory. On many systems, the operating system reclaims resources after the process makes the exit system call.
Controlling access
The omission of releasing a resource when a program has finished using it is known as a resource leak, and is an issue in sequential computing. Multiple processes wish to access a limited resource can be an issue in concurrent computing, and is known as resource contention. Resource management seeks to control access in order to prevent both of these situations.
Resource leak
Formally, resource management (preventing resource leaks) consists of ensuring that a resource is released if and only if it is successfully acquired. This general problem can be abstracted as "before, body, and after" code, which normally are executed in this order, with the condition that the after code is called if and only if the before code successfully completes, regardless of whether the body code executes successfully or not. This is also known as execute around or a code sandwich, and occurs in various other contexts, such as a temporary change of program state, or tracing entry and exit into a subroutine. However, resource management is the most commonly cited application. In aspect-oriented programming, such execute around logic is a form of advice. In the terminology of control flow analysis, resource release must postdominate successful resource acquisition; failure to ensure this is a bug, and a code path that violates this condition causes a resource leak. Resource leaks are often minor problems, generally not crashing the program, but instead causing some slowdown to the program or the overall system. However, they may cause crashes – either the program itself or other programs – due to resource exhaustion: if the system runs out of resources, acquisition requests fail. This can present a security bug if an attack can cause resource exhaustion. Resource leaks may happen under regular program flow – such as simply forgetting to release a resource – or only in exceptional circumstances, such as when a resource is not released if there is an exception in another part of the program. Resource leaks are very frequently caused by early exit from a subroutine, either by a return statement, or an exception raised either by the subroutine itself, or a deeper subroutine that it calls. While resource release due to return statements can be handled by carefully releasing within the subroutine before the return, exceptions cannot be handled without some additional language facility that guarantees that release code is executed. More subtly, successful resource acquisition must dominate resource release, as otherwise the code will try to release a resource it has not acquired. The consequences of such an incorrect release range from being silently ignored to crashing the program or unpredictable behavior. These bugs generally manifest rarely, as they require resource allocation to first fail, which is generally an exceptional case. Further, the consequences may not be serious, as the program may already be crashing due to failure to acquire an essential resource. However, these can prevent recovery from the failure, or turn an orderly shutdown into a disorderly shutdown. This condition is generally ensured by first checking that the resource was successfully acquired before releasing it, either by having a boolean variable to record "successfully acquired" – which lacks atomicity if the resource is acquired but the flag variable fails to be updated, or conversely – or by the handle to the resource being a nullable type, where "null" indicates "not successfully acquired", which ensures atomicity.
Resource contention
In computer science, resource contention refers to a conflict that arises when multiple entities attempt to access a shared resource, like random access memory, disk storage, cache memory, internal buses, or external network devices.
Memory management
Memory can be treated as a resource, but memory management is usually considered separately, primarily because memory allocation and deallocation is significantly more frequent than acquisition and release of other resources, such as file handles. Memory managed by an external system has similarities to both (internal) memory management (since it is memory) and resource management (since it is managed by an external system). Examples include memory managed via native code and used from Java (via Java Native Interface); and objects in the Document Object Model (DOM), used from JavaScript. In both these cases, the memory manager (garbage collector) of the runtime environment (virtual machine) is unable to manage the external memory (there is no shared memory management), and thus the external memory is treated as a resource, and managed analogously. However, cycles between systems (JavaScript referring to the DOM, referring back to JavaScript) can make management difficult or impossible.
Lexical management and explicit management
A key distinction in resource management within a program is between lexical management and explicit management – whether a resource can be handled as having a lexical scope, such as a stack variable (lifetime is restricted to a single lexical scope, being acquired on entry to or within a particular scope, and released when execution exits that scope), or whether a resource must be explicitly allocated and released, such as a resource acquired within a function and then returned from it, which must then be released outside of the acquiring function. Lexical management, when applicable, allows a better separation of concerns and is less error-prone.
Basic techniques
The basic approach to resource management is to acquire a resource, do something with it, then release it, yielding code of the form (illustrated with opening a file in Python): from typing import TextIO f: TextIO = open(filename) ... f.close() This is correct if the intervening ... code does not contain an early exit ( return ), the language does not have exceptions, and open is guaranteed to succeed. However, it causes a resource leak if there is a return or exception, and causes an incorrect release of unacquired resource if open can fail. There are two more fundamental problems: the acquisition-release pair is not adjacent (the release code must be written far from the acquisition code), and resource management is not encapsulated – the programmer must manually ensure that they are always paired. In combination, these mean that acquisition and release must be explicitly paired, but cannot be placed together, thus making it easy for these to not be paired correctly. The resource leak can be resolved in languages that support a finally construction (like Python) by placing the body in a try clause, and the release in a finally clause: from typing import TextIO f: TextIO = open(filename) try: ... finally: f.close() This ensures correct release even if there is a return within the body or an exception thrown. Further, note that the acquisition occurs before the try clause, ensuring that the finally clause is only executed if the open code succeeds (without throwing an exception), assuming that "no exception" means "success" (as is the case for open in Python). If resource acquisition can fail without throwing an exception, such as by returning a form of null , it must also be checked before release, such as: from typing import TextIO f: TextIO = open(filename) try: ... finally: if f: f.close() While this ensures correct resource management, it fails to provide adjacency or encapsulation. In many languages there are mechanisms that provide encapsulation, such as the with statement in Python: with open(filename) as f: ... The above techniques – unwind protection ( finally ) and some form of encapsulation – are the most common approach to resource management, found in various forms in C#, Common Lisp, Java, Python, Ruby, Scheme, and Smalltalk, among others; they date to the late 1970s in the NIL dialect of Lisp; see . There are many variations in the implementation, and there are also significantly different approaches. 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. However, it is also possible to manage only the object that directly uses the resource, and not use resource management on wrapper objects: try (FileInputStream stream = new FileInputStream(fileName)))) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // Use reader. } // stream is closed when the try-with-resources block is exited. // reader is no longer usable after stream is closed, but so long as it does not escape the block, this is not a problem. By contrast, in Python, a csv.reader does not own the file that it is reading, so there is no need (and it is not possible) to close the reader, and instead the file itself must be closed. import csv from typing import Iterator with open(filename) as f: r: Iterator[list[str = 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. In .NET, convention is to only have direct user of resources be responsible: "You should implement IDisposable only if your type uses unmanaged resources directly." 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); for example, the lapsed listener problem can occur and cause resource leaks if using the observer pattern (and observers hold resources). Various mechanisms exist to allow greater control of resource management. For example, in the Google Closure Library, the goog.Disposable class provides a registerDisposable method to register other objects to be disposed with this object, together with various lower-level instance and class methods to manage disposal.
See also
Memory management Pool (computer science)
References
Further reading
DG Update: Dispose, Finalization, and Resource Management, Joe Duffy
External links
Deterministic Resource Management, WikiWikiWeb
Text derived from https://en.wikipedia.org/w/index.php?oldid=1364230393 under CC BY-SA 4.0; modifications have been made.