Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java try with resources

farenda 2015-06-24 0

Problem:

Java 7 finally has shipped try with resources construct that simplifies very common use case when developer had to open some resource and then close in finally block after usage. try with resources makes it very simple. Learn how!

Solution:

The following example shows the problem with the old, verbose approach and the new one, available since Java 7:

package com.farenda.java;

public class TryWithResources {

    static class CostlyResource implements AutoCloseable {

        public static CostlyResource open() {
            System.out.println("CostlyResource.open()");
            return new CostlyResource();
        }

        @Override
        public void close() {
            System.out.println("CostlyResource.close()");
        }
    }

    public static void main(String[] args) {
        tryWithFinally();
        tryWithResources();
    }

    private static void tryWithFinally() {
        CostlyResource resource = null;
        try {
            resource = CostlyResource.open();
            System.out.println("Old way: try with finally");
        } finally {
            // Have to check and call close() manually:
            if (resource != null) {
                resource.close();
            }
        }
    }

    private static void tryWithResources() {
        // CostlyResource.close() will be automatically called
        // at the and of the "try" block
        try (CostlyResource resource = CostlyResource.open()) {
            System.out.println("Java 7 way: Try with resources");
        }
    }
}

In the example I’ve created a sample resource – CostlyResource. It works the same as any other implementations of java.lang.AutoCloseable. As you can see the new version is much sorter and makes code more readable.

Running the code gives the following output:

CostlyResource.open()
Old way: try with finally
CostlyResource.close()
CostlyResource.open()
Java 7 way: Try with resources
CostlyResource.close()

Enjoy the new Java 7 feature! :-)

Share with the World!
Categories Java Tags java-basics
Previous: Spock Framework Maven Gradle Setup
Next: Bash until loop

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored