Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RAII possible in Java?

Tags:

java

raii

http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

Is this design pattern possible in Java? If so, how? If not, why not?

Thanks!

like image 881
anon Avatar asked Aug 04 '26 04:08

anon


1 Answers

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).

like image 140
Thilo Avatar answered Aug 06 '26 16:08

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!