Skip to main content

try-with-resources statement improvement

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
No replies
rdabrowa
Offline
Joined: 2008-03-06

I like the concept of the new try-with-resources statement. It goes towards C++ automatic variables idea combined with destructors. In C++, a programmer may define a local variable and may be sure that some automatic cleanup (like closing of a stream) will be invoked by variable destructor when code goes out of scope. The close method of AutoCloseable interface mimics the C++ destructor, invoked at leave of try-with-resources scope. But, what do you think about slightly different solution of the problem...

I'm thinking about a solution similar to the proposed below:

  • declaration of object reference may be preceded by auto keyword; let's name such type of reference an auto reference
  • the auto keyword has no effect for types which don't implement AutoCloseable interface
  • When the program reaches end of scope, in which the auto reference variable is defined, close() method is invoked on object held by reference at this moment. For example:
{
    auto BufferedReader br = new BufferedReader(fileReader);
}    // br.close() is invoked here<br />
  • Assignment to an auto reference invokes close on object held by reference before assignment. More precisely, the following assignment to auto reference:
aref = &lt;&lt;expression&gt;&gt;;

would correspond to the following operations on usual reference:
if( aref != null ) {
    aref.close();
    aref = null;
}
aref = &lt;&lt;expression&gt;&gt;;

Advantages:

  • enclosing with try block is not necessary
  • objects may be created anywhere in a method, not only at beginning of a try block

For example, consider the code:

static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}

This might be written using the syntax proposed:
static String readFirstLineFromFile(String path) throws IOException {
  auto BufferedReader br = new BufferedReader(new FileReader(path));
  return br.readLine();
}

Example 2:
static void copy(String src, String dest) throws IOException {
  try (InputStream in = new FileInputStream(src);
       OutputStream out = new FileOutputStream(dest)) {
    byte[] buf = new byte[8192];
    int n;
    while ((n = in.read(buf)) &gt;= 0)
      out.write(buf, 0, n);
  }
}

With the proposed syntax it may look like:
static void copy(String src, String dest) throws IOException {
  auto InputStream in = new FileInputStream(src);
  auto OutputStream out = new FileOutputStream(dest);
  byte[] buf = new byte[8192];
  int n;
  while ((n = in.read(buf)) &gt;= 0)
    out.write(buf, 0, n);
}

If introduction of the auto keyword is unacceptable, some annotation might be used instead.
What do you think about this solution?