RAII stands for “Resource Acquisition Is Initialisation” and is a design pattern in the C++ where acquisition of Operating System level resources such as file handles, sockets, etc is associated with initialisation of a C++ object, and the release of these objects is associated with the destruction of the C++ objects. It is a common idiom which works very well in C++.

It does not work well in Java and most other languages which automatically manage memory. Why?

The underlying reason is that the O/S level resources tend to be far more precious then small amounts of memory they get associated with. For example, an C++ application could associate an opened serial port with a small object only ~100 bytes of memory. It typically does not care about memory but it is important to release the serial port as soon as the work is done so other applications can use it.

Garbage collected languages obviously are optimised to handle memory management with the garbage collector. In such languages it is typically very inefficient to try to free every bit of memory as soon as it can no longer be reached – and it is also unnecessary since small accumulation of unused memory will typically not affect programs at all. Hence, garbage collection happens at intervals, and even then, not every bit of unneeded memory is collected at every interval.

And this works very well – but only as far as memory is concerned. But if you are relying on destruction and clean-up of objects to free up a precious system resource it wont work too well…