http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
Is this design pattern possible in Java? If so, how? If not, why not?
Thanks!
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
Is this design pattern possible in Java? If so, how? If not, why not?
Thanks!
The same Wikipedia page that you linked to has a section on Java, quote:
Hence the "finalize" method of an unreferenced object might be never called or called only long after the object became unreferenced. Resources must thus be closed manually by the programmer, using something like the dispose pattern.
void java_example() {
// open file (acquire resource)
final LogFile logfile = new LogFile("logfile.txt");
try {
logfile.write("hello logfile!");
// continue using logfile ...
// throw exceptions or return without worrying about closing the log;
// it is closed automatically when exiting this block
} finally {
// explicitly release the resource
logfile.close();
}
}
The burden of releasing resources falls on the programmer each time a resource is used.
I think there is a proposal for Java 7, which would create Closeable classes, and some syntactic sugar for the try
blocks to make this more concise (but you still have to write that try
block).