Free degree-level programming lessons for careful independent study.

Degree Level Programmes · Programming 2 · Lesson 16

Resource Lifecycle and Cleanup

Understand cleanup as a lifecycle issue: files, streams and resources should be closed when their useful extent ends.

Lesson Overview

Understand cleanup as a lifecycle issue: files, streams and resources should be closed when their useful extent ends.

Portfolio focus: Use try-with-resources in a tiny example.

ConceptResource management
Run fileResourceLifecycleCleanupDemo.java
BaselineAda
Evidence3 tasks

Starter: think before typing

Before running this resource management example, find the line where the main idea becomes active. Write a prediction: what must already be true for that line to work, and what should be different after it runs? The checked run ends with `Ada`; predict how the focus line helps produce that evidence.

Learning Objectives

  • Explain why cleanup matters even in a garbage-collected language.
  • Use try-with-resources.
  • Distinguish object memory from external resources.
  • Design code that makes cleanup hard to forget.

Learning Outcomes

  • By the end of the lesson, you can explain why cleanup matters even in a garbage-collected language.
  • By the end of the lesson, you can use try-with-resources.
  • By the end of the lesson, you can distinguish object memory from external resources.
  • By the end of the lesson, you can design code that makes cleanup hard to forget.

Why this idea exists

Resource lifecycle matters because some things a program uses are not ordinary memory: files, streams, sockets, database connections and handles may remain open outside the garbage-collected object model.

Older languages often made cleanup the programmer's direct responsibility, and failures could leak memory or lock resources. Java reduced some of that burden, but constructs such as try-with-resources exist because external resources still need deterministic cleanup.

This lesson fits the arc by widening responsibility from values and objects to the environment around the program. A reliable program must finish its work cleanly, not just produce the right line of output.

Deep dive

Mechanism in this example

The important mechanism is visible around `try (DemoResource resource = new DemoResource("Ada")) {`. Read it as a concrete move in the program, not as decorative syntax: identify what value, object, branch, call or boundary is being created at that point.

Design pressure

This lesson fits the arc by widening responsibility from values and objects to the environment around the program. A reliable program must finish its work cleanly, not just produce the right line of output.

Failure mode to watch

For Resource Lifecycle and Cleanup, deliberately disturb the assumption behind `try (DemoResource resource = new DemoResource("Ada")) {`: use an awkward value, missing input, wrong order of calls or boundary case. The useful question is how that disturbance exposes a weakness in the resource management design.

Extension step

Extend the example by doing this: Explain what gets cleaned up. The point is to make one small change that forces you to revisit the concept, rather than adding unrelated features.

Portfolio standard

The portfolio note should not repeat the lesson wording. It should show the edited code, the run result, and your own explanation of this evidence: compare java cleanup with the idea of destructors in c++.

Lesson visual

A lifecycle timeline showing open file, useful work, automatic close, and a warning about resources outside ordinary object memory.
A lifecycle timeline showing open file, useful work, automatic close, and a warning about resources outside ordinary object memory.Download visual

Type this and run it

Create ResourceLifecycleCleanupDemo.java, type the program, and run it before changing anything. This section is about reproducing the checked baseline.

public class ResourceLifecycleCleanupDemo {
  public static void main(String[] args) {
    try (DemoResource resource = new DemoResource("Ada")) {
      System.out.println(resource.read());
    }
  }

  static class DemoResource implements AutoCloseable {
    private final String value;

    DemoResource(String value) {
      this.value = value;
    }

    String read() {
      return value;
    }

    public void close() {
      // Real resources would release a file, stream or socket here.
    }
  }
}

Build and run it with:

javac ResourceLifecycleCleanupDemo.java && java ResourceLifecycleCleanupDemo

Expected baseline: Ada

Run the code in your browser

Use the editor as an experiment surface. First run the checked version, then make one small change to the part of the program that demonstrates resource management and compare the new behaviour with the reference output.

Line-by-line explanation

Read the code as a sequence of responsibilities. The focus line for this lesson is try (DemoResource resource = new DemoResource("Ada")) {; the surrounding lines prepare it, use its result or make the behaviour observable.

public class ResourceLifecycleCleanupDemo {

This names the runnable class for the Resource Lifecycle and Cleanup example, giving the compiler and JVM one clear unit to build.

public static void main(String[] args) {

This is the program entry point. In Resource Lifecycle and Cleanup, it keeps the demonstration of resource management in one traceable starting script.

try (DemoResource resource = new DemoResource("Ada")) {

This try line, `try (DemoResource resource = new DemoResource("Ada")) {`, marks the Resource Lifecycle and Cleanup boundary between ordinary work and failure or cleanup behaviour.

System.out.println(resource.read());

This prints resource.read() as the observable evidence for Resource Lifecycle and Cleanup. The output lets the learner check whether the resource management idea behaved as predicted.

}

This closes the innermost Resource Lifecycle and Cleanup block, so the immediately preceding method, branch or loop has finished.

}

This closes the outer Resource Lifecycle and Cleanup structure, returning the reader to the surrounding class or file.

static class DemoResource implements AutoCloseable {

This starts a supporting class so Resource Lifecycle and Cleanup can separate the lesson idea into its own named responsibility.

private final String value;

This declares value as object state for the Resource Lifecycle and Cleanup design without exposing it directly. Later constructors or methods should give it a controlled value.

DemoResource(String value) {

This constructor prepares a new object so the Resource Lifecycle and Cleanup example can use it in a valid state.

this.value = value;

This assignment changes value in Resource Lifecycle and Cleanup to value. Trace where that new value is used next.

}

This closing brace number 3 completes another layer of the Resource Lifecycle and Cleanup source structure Java has been checking.

String read() {

This starts read, a named Resource Lifecycle and Cleanup operation. Its parameters describe what information comes in; its body decides what work is done.

return value;

This sends a Resource Lifecycle and Cleanup result back to the caller, so the surrounding code can use the answer.

}

This closing brace number 4 completes another layer of the Resource Lifecycle and Cleanup source structure Java has been checking.

public void close() {

This starts close, a named Resource Lifecycle and Cleanup operation. Its parameters describe what information comes in; its body decides what work is done.

// Real resources would release a file, stream or socket here.

This resource lifecycle and cleanup line supports the surrounding example. Explain the exact value, name or block it affects before moving on.

Worked example

From code to explanation

Problem: Use Resource Lifecycle and Cleanup to complete a small portfolio-quality step: Use try-with-resources in a tiny example.

Method: Locate the line `try (DemoResource resource = new DemoResource("Ada")) {`, explain the exact role it plays, then decide what you would change to extend the example without changing the whole program.

Reveal worked answer

The checked run should produce `Ada`. A strong answer links the result back to resource management: what was created, selected, stored, called or protected, and why that matters for the portfolio task.

Trace the program

Before: Before the key operation, identify the relevant value, object, branch or resource that the resource management concept depends on.

During: Trace `try (DemoResource resource = new DemoResource("Ada")) {` as the Resource Lifecycle and Cleanup example executes. Say whether that operation creates data, checks a condition, calls behaviour, stores information or crosses a boundary.

After: Compare the run with the expected evidence: `Ada`.

Change: Now explain what gets cleaned up, run again, and explain the smallest reason the behaviour changed.

Common misconception

A common mistake in resource lifecycle and cleanup is treating the example as a finished answer. For resource management, the important question is narrower: which operation carries the idea, what does it make possible, and what would break if you changed it carelessly?

Quick checks

1. In this Resource Lifecycle and Cleanup example, what is the best reason to focus on `try (DemoResource resource = new DemoResource("Ada")) {`?

2. Which evidence is strongest after you edit and rerun this example?

How to study this lesson

For Resource Lifecycle and Cleanup, predict how resource management changes the run before you press Run.

Use the first portfolio task as your main edit: Use try-with-resources in a tiny example.

Use the second task as your variation: Explain what gets cleaned up.

Finish with evidence, not a diary entry: Compare Java cleanup with the idea of destructors in C++.

Portfolio Practice

  1. Use try-with-resources in a tiny example.
  2. Explain what gets cleaned up.
  3. Compare Java cleanup with the idea of destructors in C++.

Final self-check

Can you explain the key operation?

Explain the line identified in the quick check in one or two sentences. Your answer should say what it does before the output Ada appears.

Can you justify the portfolio evidence?

Your evidence should include the original run, one edited run, and a short note explaining how the edit affected resource management.

Study route

Practise resource management by predicting the Java example, typing it, running it in the browser, tracing the result and saving portfolio evidence.

Next, move into Design Patterns in Practice and carry forward one improvement from this lesson into the next program.