I am not sure there is a common way this is handled, because it takes a lot of work and discipline to do it right, and most people would rather leave open the possibility of error than discipline themselves.
I like to experiment, especially with ways of reducing the possibility of error, so from time to time I have been using various techniques.
One technique is the "hand-off" pattern: whenever a closeable resource is passed from object A to object B, a "handOff" boolean flag is also passed, telling object B whether it should dispose of the resource when it is done with it. I am not terribly satisfied with it, because it is not enforceable at all: the holder of the resource may do the exact opposite of what the "handOff" parameter suggests.
Another technique which is halfway enforceable is using the type system to its fullest extent: if you are given a disposable resource, you must always dispose it. If you are not going to dispose it, then it should not be disposable. In other words, if it is not disposable, then you cannot dispose it.
Unfortunately, the JRE has not been designed with this in mind, so you have to redo a lot of classes and interfaces for it to work. For example, InputStream
is a class which implements Closeable
. So, if you were to use the type system technique with this class as it is, it would mean that whenever you would pass an InputStream
to someone you would have to kiss it bye-bye.
So, classes like InputStream
would have to be reworked as follows:
An InputStreamResource
class is introduced, fully encapsulating the original InputStream
class of the JRE; A new InputStream
interface is introduced, containing all the methods of the original InputStream
class, except Close()
; then, InputStreamResource
is made to implement the new InputStream
interface, and the Closeable
interface. Thus, anyone accepting an InputStreamResource
promises to close it, while anyone accepting an InputStream
interface is simply unable to close it, because it is not Closeable
.