2

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

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

Thanks!

anon
  • 41,035
  • 53
  • 197
  • 293

2 Answers2

11

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

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
Thilo
  • 257,207
  • 101
  • 511
  • 656
1

With multiple resource acquisitions within the same scope, you would need the approach, which is carefully designed to be robust, within the article:

http://www.javalobby.org/java/forums/t19048.html

which is summarized below.

final Connection conn = ...;
try {
    final Statement stmt = ...;
    try {
        final ResultSet rset = ...;
        try {
            //use resources.
        }
        finally {rset.close();}
    }
    finally {stmt.close();}
}
finally {conn.close();}

Do read the original link to understand why it needs to be this way and why anything else, like the one proposed in the other answers, would not suffice.

kirakun
  • 2,770
  • 1
  • 25
  • 41