Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This question already has an answer here:

A buddy said today that one change between v6 and v7 is that v7 will close for instance database connection "automatically" but couldn't JBoss do that already with Java 5? I've seen "JBoss is closing the connection for you." in the JBoss' logs many years ago with Java 5 (or even 4). What do you think? I almost read the same question here but not exactly:

How to justify migration from Java 6 to Java 7?

The answer to the question above does not list the feature we were talking about this morning. What did my buddy mean? What do you think is the one or the few major technical changes? I understand Java 6 has not even support anymore but that is a policy and not the diff analyses between v6 and v7.

share|improve this question

marked as duplicate by gnat, Kilian Foth, Yusubov, Corbin March, World Engineer Sep 4 '13 at 18:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3  
this is try-with-resources feature, explained in details in at least two of the answers in the justify migration question you refer to (1, 2) –  gnat Sep 3 '13 at 15:42

1 Answer 1

up vote 5 down vote accepted

That feature name is automatic resource management of the Project Coin it works for streams and connections:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
} 

Becomes:

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)) >= 0)
            out.write(buf, 0, n);
    }
}
share|improve this answer
1  
Thank you. That looks very good. –  Niklas Rtz Sep 3 '13 at 16:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.