Pages

Friday, January 10, 2014

How to Balance Resources?

Most of the time, the resource usage in a system follows a specific pattern: we allocate resources, use them and then deallocate it. But many developers have no consistent plan for dealing with resource allocation. So, here is a simple tip:

Finish What You Start…

This means that the routine or object which allocate the resources is also responsible for deallocating it.

Nested Allocation

When the routines require more than one resource, consider the following two suggestions:

  1. Deallocate resources in the opposite order in which we allocate them. If one resource contains reference to another, this will ensure that no orphaned resources are there in the system.
  2. When we allocate the same set of resources at different places, always allocate them in the same order. This will reduce the possibility of deadlocks happening in the system.

Objects and Exceptions

Classes can be used for allocating and deallocating resources. We can encapsulate resources in a class. When we need a particular resource type, instantiate an object of that class. When an object is created, the constructor allocates the resources. When the object goes out of scope, or is reclaimed by the garbage collector, the object's destructor then deallocates the wrapped resource.

This approach is particularly useful while working with languages like C++.



- summary of How to Balance Resources, from The Pragmatic Programmer: from Journeyman to Master

No comments:

Post a Comment