Resource: Acquire, Use and Release

Acquire something, use it, and release it however the work ends.

"And yet all this comes down when the job's done"

— Seamus Heaney, Scaffolding

A Resource is that scaffolding: put up before the work, and taken down after it, even when the job fails.

What You'll Learn

  • Describe how to acquire and release something, and use it in a VTask that releases it when the task is done
  • Say what is reported when the use fails, the release fails, or both do
  • Compose resources that release in reverse order, and use one Resource many times
  • Add finalisers, and an action that runs only when the use fails, such as a rollback
  • Hold a resource while a Scope's tasks use it

See Example Code

The code on this page is ResourceBook.java: the page includes it, so the build compiles and runs it. ResourceBookTest.java holds what the page says each method does.


Acquire, use, release

Java's try-with-resources closes a resource when its block ends. A VTask describes work that runs later, so a try around building one closes the resource before the work has started. A Resource<A> describes how to acquire an A and how to release it. use gives a VTask that, each time it runs, acquires, runs the task you give it, and releases what it acquired, whether that task succeeded, failed or was cancelled. This is the acquire-use-release, or bracket, pattern.

The code on this page uses these imports, with Order from the order records the Optics chapter introduces:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.hkt.vtask.Resource;
import org.higherkindedj.hkt.vtask.VTask;

Booking a courier happens on a session, which is opened first and must be closed after. Session stands in for one, and logs what happens to it:

  // A booking session with the courier, which logs what happens to it
  record Session(String id, List<String> log) implements AutoCloseable {
    String book(Order order) {
      log.add("book on " + id);
      return "booked on " + id;
    }

    @Override
    public void close() {
      log.add("close " + id);
    }
  }

  // Each use opens a session of its own
  static Resource<Session> sessions(List<String> log) {
    AtomicInteger opened = new AtomicInteger();
    return Resource.fromAutoCloseable(
        () -> {
          Session session = new Session("session-" + opened.incrementAndGet(), log);
          log.add("open " + session.id());
          return session;
        });
  }

ORDER is a paid order:

    List<String> log = new CopyOnWriteArrayList<>();
    Resource<Session> session = sessions(log);
    VTask<String> booking = session.use(s -> VTask.of(() -> s.book(ORDER)));

    int openedBeforeRunning = log.size();
    // 0
    booking.run();
    List<String> whatRan = List.copyOf(log);
    // [open session-1, book on session-1, close session-1]

Building the task opens nothing. Each run opens a session, books on it, and closes it, so running booking again opens session-2. useSync(f) does the same with a plain function rather than one that gives a task.

stateDiagram-v2
    accTitle: What happens to a resource during one use
    accDescr: A use acquires the resource. If the acquire fails, nothing is held, and nothing is released. Otherwise the resource is held while its task runs. If the task succeeds, the release runs. If the task fails or is cancelled, the onFailure actions run first, then the release. The finalisers run after the release, and the use ends with the task's result or its failure.
    state "the acquire failed" as NotHeld
    state "held" as Held
    state "the task succeeded" as Succeeded
    state "the task failed or was cancelled" as Failed
    state "the onFailure actions ran" as RolledBack
    state "released" as Released
    [*] --> NotHeld
    NotHeld --> [*] : nothing to release
    [*] --> Held : acquire
    Held --> Succeeded
    Held --> Failed
    Failed --> RolledBack
    Succeeded --> Released : release
    RolledBack --> Released : release
    Released --> [*] : finalisers
    classDef domain fill:#a6d189,stroke:#40a02b,color:#232634
    classDef step fill:#8caaee,stroke:#1e66f5,color:#232634
    classDef error fill:#e78284,stroke:#d20f39,color:#232634
    class Held domain
    class Succeeded step
    class Released step
    class NotHeld error
    class Failed error
    class RolledBack error

The diagram shows that every way out of a held resource passes through its release, after the onFailure actions when the task fails, and before the finalisers. If the acquire fails, nothing is held, so neither the release, the onFailure actions nor the finalisers run.

Creating a resource

FactoryWhat it describesFor
Resource.fromAutoCloseable(acquire)An AutoCloseable, closed after each useConnections, sessions, streams, channels
Resource.make(acquire, release)An acquire and a release of your ownLocks, handles, anything without close()
Resource.pure(value)A value with nothing to releaseConfiguration, or a constant in a composition

The acquire is a Callable, so it may throw a checked exception. A Resource never holds null: pure(null) throws at the call, and an acquire or a map function that returns null fails the use with a NullPointerException. Hold a value that may be absent as a Maybe, and acquire it with make.

When the use fails

The session is closed whatever happens to the booking. These are the extra imports:

import java.io.IOException;
import org.higherkindedj.hkt.trymonad.Try;
    log.clear();
    Try<String> refused =
        session.use(s -> VTask.<String>fail(new IOException("the courier refused"))).runSafe();
    // Failure(java.io.IOException: the courier refused)
    List<String> closedAnyway = List.copyOf(log);
    // [open session-2, close session-2]

When the release throws as well, the use's failure is still the one reported, and the release's exception is suppressed onto it, as try-with-resources does. After a successful use, a release that throws fails the use with its own exception, so a writer whose final flush fails does not report success.

For fromAutoCloseable, the release is close(), which may throw a checked exception. The task that use returns reports it as it reports any checked failure: run() throws it wrapped in a VTaskExecutionException, and runSafe() holds it unwrapped.

A cancelled use is a failed one, so its resource is released too. The release runs with the thread's interrupt status cleared, so a cancellation does not cut a blocking release short, and the status is restored afterwards.

Composing resources

and holds two resources at once, acquiring them in order and releasing them in reverse. flatMap acquires a second resource from the first, as try-with-resources nests a statement inside its connection, and releases the second first. Releasing in reverse means a resource that depends on another is released before the one it depends on. If a later acquire fails, the ones already held are released before the failure is reported. These are the extra imports:

import org.higherkindedj.hkt.vtask.Par;
    log.clear();
    Resource<Par.Tuple2<Session, Session>> twoSessions = session.and(session);

    twoSessions.useSync(both -> both.first().book(ORDER) + ", " + both.second().book(ORDER)).run();
    List<String> inReverse = List.copyOf(log);
    // [open session-3, open session-4, book on session-3, book on session-4, close session-4,
    //   close session-3]

    // A shipping label printed on a session, voided after use
    log.clear();
    Resource<String> label =
        session.flatMap(s -> Resource.make(() -> s.id() + "-label", l -> log.add("void " + l)));

    label.useSync(String::length).run();
    List<String> labelFirst = List.copyOf(log);
    // [open session-5, void session-5-label, close session-5]

and gives a Par.Tuple2, a preview class, so code that calls and needs --enable-preview, whether or not it names Par, as the VTask page explains. and(second, third) holds three at once, as a Par.Tuple3. A Resource composed with flatMap or and reports a failed release as a RuntimeException, whose cause is the exception from the outermost release that threw.

map(f) changes the value a resource gives, and its release still receives the value the acquire returned. map takes a plain Function, so a checked exception has to be handled inside f.

Using one resource many times

A Resource holds nothing itself. Each use acquires its own resource and releases exactly that one. So build a Resource once and use it wherever it is needed: once per request, on several threads at once, or one use nested inside another. This holds however the Resource was composed:

    log.clear();
    Resource<String> sessionIds = session.map(Session::id);

    List<String> both =
        sessionIds
            .use(outer -> sessionIds.use(inner -> VTask.succeed(List.of(outer, inner))))
            .run();
    // [session-6, session-7]
    List<String> innermostFirst = List.copyOf(log);
    // [open session-6, open session-7, close session-7, close session-6]

The nested use opens a second session, and each use closes the one it opened, innermost first. The use sees each session's id, and the release still closes the Session itself.

Finalisers

withFinalizer(action) adds an action that runs after the release:

    List<String> steps = new ArrayList<>();
    Resource<String> handle =
        Resource.make(() -> "handle", _ -> steps.add("release"))
            .withFinalizer(() -> steps.add("log the release"))
            .withFinalizer(() -> steps.add("record metrics"));

    handle.useSync(String::length).run();
    List<String> ranInOrder = List.copyOf(steps);
    // [release, log the release, record metrics]

Finalisers run in the order they were added, and each runs even when the release, or an earlier finaliser, throws. When the release and a finaliser both throw, the release's exception is reported, with the finaliser's suppressed onto it.

Rolling back on failure

onFailure(action) adds an action that runs when the use fails, before the release. It receives the acquired resource, so it can undo partial work, such as rolling back a transaction. When the use succeeds, only the release runs:

    List<String> ledger = new ArrayList<>();
    AtomicInteger begun = new AtomicInteger();
    Resource<String> transaction =
        Resource.make(() -> "tx-" + begun.incrementAndGet(), tx -> ledger.add("close " + tx))
            .onFailure(tx -> ledger.add("rollback " + tx));

    transaction.useSync(String::length).run();
    transaction.use(_ -> VTask.fail(new IllegalStateException("insert failed"))).runSafe();
    List<String> whatRanEachTime = List.copyOf(ledger);
    // [close tx-1, rollback tx-2, close tx-2]

The first use succeeds, so it only closes tx-1. The second fails, so tx-2 is rolled back and then closed. The use fails when the function given to use throws, or the task it returns fails. A cancelled task fails too. A step composed after onFailure counts as well, when it fails while the resource is held:

  • map's or flatMap's function throws.
  • The next acquire in flatMap or and fails.

The action runs before its Resource's release and before the finalisers added to it. Actions added one after another run most recently added first. If an action throws, the release still runs, and the use's failure is still the one reported.

With a Scope

A resource can be held while a Scope's tasks use it, and is released once the scope has joined them all. This is the extra import:

import org.higherkindedj.hkt.vtask.Scope;
    log.clear();
    VTask<List<String>> bookTwice =
        session.use(
            s ->
                Scope.<String>allSucceed()
                    .fork(VTask.of(() -> s.book(ORDER)))
                    .fork(VTask.of(() -> s.book(ORDER)))
                    .join());

    List<String> bookings = bookTwice.run();
    // [booked on session-8, booked on session-8]
    List<String> closedAfterBoth = List.copyOf(log);
    // [open session-8, book on session-8, book on session-8, close session-8]

A resource the tasks share must be safe to use from several threads at once, as the session's log is here. Add an onFailure rollback, as in Rolling back on failure, and this shape runs a transaction's steps at the same time. When one step fails, the scope cancels the others, the rollback runs, then the release.

Methods

MethodWhat it does
Resource.fromAutoCloseable(acquire), make(acquire, release), pure(value)Describe a resource, acquiring nothing
use(f)Gives a VTask that acquires, runs the task f gives for the resource, and releases
useSync(f)The same, where f gives a plain value rather than a task
map(f)Changes the value the resource gives
flatMap(f), and(other), and(second, third)Hold resources together, releasing them in reverse order
withFinalizer(action)Runs action after the release
onFailure(action)Runs action on the resource when the use fails, before the release

When to use Resource

You needUse
Something acquired and released around a VTask, however it endsResource
A resource used within one block of ordinary codeJava's try-with-resources
Cleanup after a task, with nothing to acquireguarantee on a VTaskPath
The same around an IObracket or withResource on an IOPath
A release that sees whether a typed result succeededbracketOutcome on a VResultPath

Hands-On Learning

Practise Resource in TutorialResource (10 exercises), part of the Scope & Resource journey.


Previous: Structured Concurrency Next: Shared State