<!-- description: Share state between Java virtual-thread tasks with Ref, hand a value to another task with Promise, and run a task once for all its readers with VTask.memoize. -->

# Ref and Promise: Shared State

_Keep a count, hand a value over, and work something out once, without leaving the effect._

<!-- source: Samuel Beckett, Waiting for Godot (Grove Press, 1954), Act I; wording checked against quotation sites only -->
> _"Let's go." "We can't." "Why not?" "We're waiting for Godot."_
>
> — Estragon and Vladimir, *Waiting for Godot*

Vladimir and Estragon are reading a `Promise` that nobody completes: they cannot leave until the value comes. A task waiting on one waits the same way, but it stops when it is interrupted.

~~~admonish info title="What You'll Learn"
- Keep state that tasks running at the same time share, in a `Ref` whose reads and writes are tasks
- Take a number and move the count on in one step with `modify`, and keep its function pure
- Hand a value from one task to others with a `Promise`, completed once and read many times
- Run a task once and share its result with every branch that needs it, with `memoize`, and keep or retry a failure
- Keep a `Ref`, a `Promise` or a memoised task in a `final` field, for a service built before any program runs
~~~

~~~admonish example title="See Example Code"
**The code on this page is [SharedStateBook.java](https://github.com/higher-kinded-j/higher-kinded-j/blob/main/hkj-examples/src/main/java/org/higherkindedj/example/book/foundations/sharedstate/SharedStateBook.java)**: the page includes it, so the build compiles and runs it. [SharedStateBookTest.java](https://github.com/higher-kinded-j/higher-kinded-j/blob/main/hkj-examples/src/test/java/org/higherkindedj/example/book/foundations/sharedstate/SharedStateBookTest.java) holds what the page says each method does.
~~~

---

## A count kept by many tasks {#a-count-kept-by-many-tasks}

Tasks that [`Par`](vtask_monad.md#parallel-composition-with-par) runs at the same time each return a value, and when each result is all you need, combine what `Par` returns. A count, a ticket number or a stock level that tasks read or change while the work runs needs a cell they share. In plain Java that is an `AtomicInteger` or an `AtomicReference`, whose methods act the moment they are called. A `Ref` holds the same kind of cell, but each read and write is a `VTask`. So nothing happens until the program runs, and making the cell is part of the program too. That also means `ref.set(7);` on its own does nothing: the task it returns must run.

The code on this page uses these imports, with `Order` and `LineItem` from the order records the [Optics](../optics/ch_intro.md) chapter introduces:

<!-- verify -->
```java
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.higherkindedj.example.book.optics.cast.LineItem;
import org.higherkindedj.example.book.optics.cast.Order;
import org.higherkindedj.hkt.Pair;
import org.higherkindedj.hkt.maybe.Maybe;
import org.higherkindedj.hkt.vtask.Par;
import org.higherkindedj.hkt.vtask.Promise;
import org.higherkindedj.hkt.vtask.Ref;
import org.higherkindedj.hkt.vtask.VTask;
```

Packing an order means packing each of its lines. Booking a courier gives the parcel's tracking number, the courier's token service issues a new token each time it is asked, and its depot directory counts its lookups:

```java
  // Packs one line of an order, which blocks while the warehouse works
  static VTask<LineItem> pack(LineItem line) {
    return VTask.delay(() -> line);
  }

  // Books a courier for the order, and gives the parcel's tracking number
  static VTask<String> bookCourier(Order order) {
    return VTask.delay(() -> "TRK-4471");
  }

  // Lists an order's lines for the packing slip
  static VTask<List<String>> packingList(Order order) {
    return VTask.delay(
        () -> order.lines().stream().map(l -> l.quantity() + " x " + l.sku()).toList());
  }

  // The packing slip, which needs the tracking number the booking gives
  record Slip(String customer, List<String> lines, String tracking) {}

  // The courier's token service, which issues a new token each time it is asked
  static final class TokenService {
    private final AtomicInteger issued = new AtomicInteger();

    VTask<String> fetch() {
      return VTask.delay(() -> "token-" + issued.incrementAndGet());
    }
  }

  // Asks one courier for a quote, which needs a token
  static VTask<String> quote(String courier, String token) {
    return VTask.delay(() -> courier + " with " + token);
  }

  // The courier's depot directory, which counts its lookups
  static final class DepotDirectory {
    private final AtomicInteger lookups = new AtomicInteger();

    VTask<String> nearestDepot() {
      return VTask.delay(
          () -> {
            lookups.incrementAndGet();
            return "Leeds";
          });
    }

    int lookups() {
      return lookups.get();
    }
  }

```

`ORDER` is an order for two lamps and a shade. `Ref.of(0)` gives a task that makes a cell holding 0, and `update` adds each packed line's quantity to it, from tasks running at the same time:

```java
    VTask<Integer> parcels =
        Ref.of(0)
            .flatMap(
                packed ->
                    Par.traverse(
                            ORDER.lines(),
                            line -> pack(line).flatMap(p -> packed.update(n -> n + p.quantity())))
                        .flatMap(_ -> packed.get()));

    int packed = parcels.run();
    // 3
    int packedAgain = parcels.run();
    // 3
```

No update is lost when two tasks write at once. Each run of `parcels` makes a cell of its own, so the second run counts from 0 again and gives 3, not 6.

## Taking a number with `modify` {#taking-a-number-with-modify}

`updateAndGet` gives the new value, and `getAndUpdate` the one it replaced. `modify` gives anything worked out from the value, and stores the new value, in one atomic step. Its function returns a `Pair`: the new value first, then the result. Handing out tracking numbers, so that no two parcels share one:

```java
    VTask<List<String>> labels =
        Ref.of(1000)
            .flatMap(
                next ->
                    Par.all(Collections.nCopies(3, next.modify(n -> Pair.of(n + 1, "TRK-" + n)))));

    List<String> numbers = labels.run().stream().sorted().toList();
    // [TRK-1000, TRK-1001, TRK-1002]
```

Each of the three tasks reads a number and leaves the next one in the cell. They take 1000, 1001 and 1002, in whichever order they run.

~~~admonish warning title="Keep an update's function pure, and the value immutable"
An update applies its function to the current value, and stores the result only if no other task has written meanwhile. If one has, the update applies the function again, to the newer value. So the function may run more than once, and anything else it does, such as logging or calling a service, may happen more than once too.

The cell guards which object it holds, not what is inside that object, and every task that reads it gets the same one. Hold an immutable value, such as a record or a `List.copyOf`, and give each update a new one: a list changed in place loses elements.
~~~

Here another task takes three lamps from the stock while the function decides:

```java
    AtomicInteger calls = new AtomicInteger();
    VTask<Integer> taken =
        Ref.of(10)
            .flatMap(
                stock ->
                    stock.updateAndGet(
                        n -> {
                          if (calls.incrementAndGet() == 1) {
                            // Stands in for another task taking three while this one decides
                            stock.set(7).run();
                          }
                          return n - 1;
                        }));

    int left = taken.run();
    // 6
    int timesRun = calls.get();
    // 2
```

The function's first answer, 9, is thrown away, and it runs again on 7. To store what a task gives, run the task first, then store its result with `set` or `update`.

## Handing a value over with `Promise` {#handing-a-value-over-with-promise}

Sometimes one task produces a value that another, running beside it, needs. Printing a packing slip needs the tracking number that booking the courier gives. A `Promise` is a cell that is completed once and read many times: `complete(value)` sets it, and `get()` waits until a value arrives. In plain Java that is a `CompletableFuture` you complete by hand. A `Promise` adds that each step is a task, and that only a value completes it: nothing can fail or cancel it, so a reader never meets an `ExecutionException`.

```java
    VTask<Slip> slip =
        Promise.<String>create()
            .flatMap(
                label ->
                    Par.map2(
                        bookCourier(ORDER).flatMap(label::complete),
                        packingList(ORDER)
                            .flatMap(
                                lines ->
                                    label
                                        .get()
                                        .map(
                                            tracking ->
                                                new Slip(
                                                    ORDER.customer().name(), lines, tracking))),
                        (_, printed) -> printed));

    Slip printed = slip.run();
    // Slip[customer=Ada, lines=[2 x LAMP, 1 x SHADE], tracking=TRK-4471]
```

`Par.map2` runs the booking and the slip at the same time. The slip's task lists the order's lines, then parks its virtual thread until the booking completes the `Promise`. Whichever finishes first, the slip holds the tracking number.

The first `complete` sets the value and gives `true`. A later one leaves the value as it was and gives `false`, rather than failing, since several tasks racing to complete one `Promise` is normal. `tryGet()` gives the value without waiting, as a [Maybe](maybe_monad.md):

```java
    Promise<String> label = Promise.<String>create().run();

    boolean first = label.complete("TRK-4471").run();
    // true
    boolean second = label.complete("TRK-9999").run();
    // false
    Maybe<String> kept = label.tryGet().run();
    // Just(TRK-4471)
```

## Running a task once with `memoize` {#running-a-task-once-with-memoize}

Every courier's quote needs a token, and fetching one for each quote wastes calls to the token service. In plain Java that is a field filled under a lock the first time it is read. `memoize()` gives a `VTask<VTask<String>>`: the outer task makes a cache, and the inner one, `token` here, runs `fetch()` once and gives the token to every later run. Runs that start while the fetch is under way wait for it.

```java
    TokenService tokens = new TokenService();
    List<String> couriers = List.of("Swift", "Parcelo", "Northwind");

    VTask<List<String>> quotes =
        tokens
            .fetch()
            .memoize()
            .flatMap(
                token -> Par.traverse(couriers, courier -> token.flatMap(t -> quote(courier, t))));

    List<String> firstRun = quotes.run();
    // [Swift with token-1, Parcelo with token-1, Northwind with token-1]
    List<String> secondRun = quotes.run();
    // [Swift with token-2, Parcelo with token-2, Northwind with token-2]
```

The three quotes share one token. The second run of `quotes` makes a new cache, so it fetches a new token. A program built once and run for each request never hands one request a token another request fetched.

~~~admonish warning title="Share the inner task"
Pass the inner task, `token`, to every branch that needs the value. Flattening it at once, as `memoize().flatMap(t -> t)`, makes a new cache on every run and caches nothing.
~~~

A failure is not cached. If the lookup fails, the runs waiting on it fail with the same exception, and the next run tries again, so a retry around a memoised task can succeed. These are the extra imports:

<!-- verify -->
```java
import java.io.IOException;
import org.higherkindedj.hkt.trymonad.Try;
```

```java
    AtomicInteger attempts = new AtomicInteger();
    VTask<String> busyOnce =
        VTask.of(
            () -> {
              if (attempts.incrementAndGet() == 1) {
                throw new IOException("the depot directory is busy");
              }
              return "Leeds";
            });
    VTask<String> depot = busyOnce.memoize().run();

    Try<String> firstTry = depot.runSafe();
    // Failure(java.io.IOException: the depot directory is busy)
    Try<String> secondTry = depot.runSafe();
    // Success(Leeds)
    Try<String> thirdTry = depot.runSafe();
    // Success(Leeds)
```

To keep a failure as well, as for a lookup that fails the same way every time, memoise a task that gives it as a value. Let a cancellation through, so that a cancelled run is still handed over rather than kept. A cancellation shows as an `InterruptedException`, one the task wrapped in an exception of its own, or any failure while the thread is interrupted:

```java
    AtomicInteger asked = new AtomicInteger();
    VTask<String> down =
        VTask.of(
            () -> {
              asked.incrementAndGet();
              throw new IllegalArgumentException("no such SKU: LAMP-9");
            });
    // Hold a failure as a value, and let a cancellation through
    VTask<Try<String>> held =
        down.map(Try::success)
            .recoverWith(
                e ->
                    e instanceof InterruptedException
                            || e.getCause() instanceof InterruptedException
                            || Thread.currentThread().isInterrupted()
                        ? VTask.fail(e)
                        : VTask.succeed(Try.failure(e)));
    VTask<Try<String>> remembered = held.memoize().run();

    Try<String> once = remembered.run();
    // Failure(java.lang.IllegalArgumentException: no such SKU: LAMP-9)
    Try<String> twice = remembered.run();
    // Failure(java.lang.IllegalArgumentException: no such SKU: LAMP-9)
    int timesAsked = asked.get();
    // 1
```

A [Lazy](lazy_monad.md) does keep a failure, because its computation is pure, and running it again would fail again.

## On a `VTaskPath` {#on-a-vtaskpath}

Each operation of a `Ref` or a `Promise` returns a plain `VTask`, so `Path.vtaskPath` lifts it onto a [`VTaskPath`](../effect/path_vtask.md), where it chains with `via` as any task does. A `VTaskPath` has `memoize()` too, which gives a path that makes a cache. These are the extra imports:

<!-- verify -->
```java
import org.higherkindedj.hkt.effect.Path;
import org.higherkindedj.hkt.effect.VTaskPath;
```

```java
    Ref<Integer> served = Ref.unsafeCreate(0);
    VTaskPath<Integer> serve = Path.vtaskPath(served.updateAndGet(n -> n + 1));

    serve.unsafeRun();
    int servedTwice = serve.unsafeRun();
    // 2

    VTaskPath<List<String>> sharedToken =
        Path.vtaskPath(new TokenService().fetch())
            .memoize()
            .via(t -> t.zipWith(t, (a, b) -> List.of(a, b)));

    List<String> bothBranches = sharedToken.unsafeRun();
    // [token-1, token-1]
```

`served` is made once, with `unsafeCreate`, which [the next section](#state-that-lives-as-long-as-a-service) explains, so both runs of `serve` count in it. `zipWith` runs its two branches at the same time, and both read the one token.

## State that lives as long as a service {#state-that-lives-as-long-as-a-service}

`Ref.of`, `Promise.create` and `memoize` make their cell when a task runs, so each run of a program has its own. A service built before any program runs, as a Spring bean is, keeps its state in `final` fields instead. `Ref.unsafeCreate` and `Promise.unsafeCreate` make the cell at once. Calling `memoize().run()` in the constructor makes the cache for the life of the service, not the value: the first dispatch looks the depot up. Like `run()`, the `unsafe` names mark where describing work turns into doing it. This is the extra import:

<!-- verify -->
```java
import org.higherkindedj.hkt.Unit;
```

```java
  // A dispatch desk, built before any program runs, keeps its state in final fields
  static final class DispatchDesk {
    private final Promise<Unit> opened = Promise.unsafeCreate();
    private final Ref<Integer> dispatched = Ref.unsafeCreate(0);
    private final VTask<String> depot;

    DispatchDesk(DepotDirectory directory) {
      // Makes the cache, not the lookup: the first dispatch looks the depot up
      this.depot = directory.nearestDepot().memoize().run();
    }

    // Opens the desk, which lets every waiting dispatch through
    VTask<Boolean> open() {
      return opened.complete(Unit.INSTANCE);
    }

    // Waits until the desk is open, then numbers the dispatch
    VTask<String> dispatch() {
      return opened
          .get()
          .then(() -> dispatched.updateAndGet(n -> n + 1))
          .flatMap(n -> depot.map(d -> "dispatch " + n + " from " + d));
    }
  }

```

`opened` is a gate: each dispatch waits on it, and `open()` lets every waiting dispatch through. Two dispatches and the opening, run at the same time, look the depot up once:

```java
    DepotDirectory directory = new DepotDirectory();
    DispatchDesk desk = new DispatchDesk(directory);
    VTask<List<String>> day =
        Par.all(List.of(desk.dispatch(), desk.dispatch(), desk.open().map(_ -> "opened")));

    List<String> log = day.run().stream().sorted().toList();
    // [dispatch 1 from Leeds, dispatch 2 from Leeds, opened]
    int lookups = directory.lookups();
    // 1
```

## Methods {#methods}

| Method | What it does |
|---|---|
| `Ref.of(value)`, `Promise.create()` | Give a task that makes a new cell each time it runs |
| `Ref.unsafeCreate(value)`, `Promise.unsafeCreate()` | Make a cell at once, for a `final` field |
| `ref.get()`, `set(value)`, `getAndSet(value)` | Read the cell, write it, or both in one step |
| `ref.update(f)`, `updateAndGet(f)`, `getAndUpdate(f)` | Apply `f` atomically, giving `Unit`, the new value or the old one |
| `ref.modify(f)` | Apply `f`, which gives a `Pair` of the new value and a result, and give the result |
| `promise.complete(value)` | Set the value if nothing has, and give whether this call did |
| `promise.get()`, `tryGet()` | Wait for the value, or give it as a `Maybe` without waiting |
| `task.memoize()`, `path.memoize()` | Give a task or a path that makes a cache and gives the memoised task or path |

## When to use which {#when-to-use-which}

| You need | Use |
|---|---|
| A count or a record that tasks running at the same time update | `Ref` |
| A value one task produces and others wait for | `Promise` |
| A task's value worked out once, however many branches ask for it | `memoize()` |
| A pure value worked out once, on first use | [Lazy](lazy_monad.md) |
| Tasks that must all succeed, joined into one value | [`Par`](vtask_monad.md#parallel-composition-with-par) |
| A resource released however the work ends | [Resource Management](vtask_resource.md) |

## The fine print {#the-fine-print}

- **A `Ref` or a `Promise` holds a value, never `null`.** `Ref.of(null)`, `set(null)` and `complete(null)` throw `NullPointerException` at the call. An update function that returns `null` fails the task, and the cell keeps its value.
- **A `Promise` holds a value, never a failure.** To hand a failure over, complete it with a value that says what went wrong, such as an [Either](either_monad.md) or a [Try](try_monad.md).
- **A reader waiting on a virtual thread parks it.** It never spins and never pins its carrier, so a thousand waiting readers leave the carriers free for the task that completes the `Promise`. `Par`, `Scope` and `runAsync` run on virtual threads; `run()` on a platform thread blocks that thread.
- **An interrupted reader stops waiting.** Its task fails with an `InterruptedException`, as `Thread.sleep` does, and the `Promise` keeps nothing of it. The loser of a `Par.race`, or a task in a [Scope](vtask_scope.md) that times out, is never left waiting.
- **Waiting runs share a memoised task's failure.** They fail with the same exception object that the run they waited on threw.
- **A cancelled run hands its work over.** A run that fails counts as cancelled when its thread is interrupted, or the failure is an `InterruptedException` or caused by one. A run waiting on it then does the work, so no run fails with an interrupt that was not its own.
- **A failure caused by an interrupt is tried again by each waiter.** It counts as a cancellation even when nothing interrupted the run, so each waiting run then tries in turn.
- **Every reader gets the same object.** Complete a `Promise`, or memoise a task, with an immutable value.
- **A memoised value never expires.** For one that does, such as a token, keep it and its expiry in a `Ref`.
- **A memoised task must not run itself.** It would wait for its own value, on its own thread or another, until it is interrupted.
- **An update's function must not run a task.** A compare-and-set loop can retry a function, but not an effect that has already happened. Run the task first, then store what it gave.

---

**Previous:** [Resource Management](vtask_resource.md)
**Next:** [VStream](vstream.md)
