# River for Java
Java 21 client and worker runtime for River's Postgres and SQLite
schemas. Jobs are ordinary River jobs: another language can insert, cancel,
retry, or work them using the same database.
## Installation
Java 21 or newer is required. Add `com.riverqueue:river:0.4.1` and a JDBC driver to your application's dependencies. Jackson 3 is included transitively.
```xml
river
https://riverqueue.com/maven
fail
false
com.riverqueue
river
0.4.1
org.postgresql
postgresql
42.7.12
```
The River repository is public and requires no credentials. Maven Central supplies third-party dependencies.
For SQLite, replace the Postgres JDBC dependency with `org.xerial:sqlite-jdbc:3.53.4.0`. To install a local copy of River from source, see the [development guide](docs/development.md#building-from-source).
## Quick start
Define job arguments as a record, give the job a stable kind, and register a
worker lambda. This complete `Example.java` starts a client, inserts a job,
waits for its completion, and stops the workers. Set `DATABASE_URL` to a
Postgres URL or a file-backed SQLite JDBC URL.
```java
import com.riverqueue.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class Example {
record SendEmail(String address, String subject) {}
public static void main(String[] args) throws Exception {
var database = Database.connect(System.getenv("DATABASE_URL"));
new Migrator(database).migrate();
var workers = new Workers()
.add(JobType.of("send_email", SendEmail.class), context -> {
System.out.println("Sending " + context.args().subject() + " to " + context.args().address());
context.output("sent");
});
var client = Client.builder(database).queue(Client.QUEUE_DEFAULT, 10).workers(workers).build();
var completed = new CompletableFuture();
try (var subscription = client.subscribe(completed::complete, Client.EventKind.JOB_COMPLETED);
var run = client.start()) {
client.insert(JobType.of("send_email", SendEmail.class),
new SendEmail("hello@example.com", "Welcome"));
System.out.println("Completed job " + completed.get(30, TimeUnit.SECONDS).job().id());
}
}
}
```
Run this demonstration against a development database with no other workers.
The worker prints a message; replace its body with your mail service. In a
service, keep the `RunHandle` open until the application stops. Each active job runs
on a virtual thread; queue limits bound concurrent jobs. In production, run
migrations as a deployment step using the CLI below.
Job kinds are explicit, stable wire names independent of Java class names.
Record properties use snake_case in JSON by default, so `accountId` becomes
`account_id`. Match kinds and JSON fields across languages sharing a job.
Use a pooled `DataSource` in applications. `Database.connect(url)` is a small
DriverManager convenience for scripts and tests and opens a physical connection
for each operation. River never closes an application-owned data source. An
[insert-only client](https://riverqueue.com/docs/insert-only-clients) is simply a
`Client` instance without a worker runtime; inserting needs no start or stop call.
## Migration CLI
SQLite connections accept `sqlite://path` and `sqlite:path`, as well as native
`jdbc:sqlite:` URLs. See the shared [SQLite URL reference](../docs/sqlite-urls.md)
for relative paths and in-memory databases.
The CLI runs with Java 21 or newer. [JBang](https://www.jbang.dev/documentation/jbang/latest/installation.html)
resolves the thin CLI JAR and its dependencies and installs a reusable command:
```sh
jbang app install --name river-java --java 21 \
--java-options=--enable-native-access=ALL-UNNAMED \
--repos https://riverqueue.com/maven --repos central \
--main com.riverqueue.cli.MigrationCli \
com.riverqueue:river-cli:0.4.1
export PATH="$HOME/.jbang/bin:$PATH"
export DATABASE_URL=postgres://localhost/myapp
# For SQLite: export DATABASE_URL=jdbc:sqlite:/absolute/path/myapp.db
river-java --help
river-java migrate-list
river-java migrate-up --dry-run
river-java migrate-up
```
Dependencies, including both JDBC drivers, are downloaded once and cached. No
`all` classifier is needed. For containers or installations with Maven and a JDK,
use the [Maven-only instructions](#running-with-maven-and-java) below, or
[build from source](docs/development.md#building-from-source).
`--database-url URL` overrides `DATABASE_URL`.
`--schema background_jobs` selects a Postgres schema; an actual migration up
creates it if needed. Listing and dry runs do not create schemas or migration tables.
| Command | Behavior |
| --- | --- |
| `migrate-up` | Applies all pending migrations, committing each separately. |
| `migrate-down` | Reverses one migration by default; may remove tables and data. |
| `migrate-list` | Lists bundled versions and whether each is applied. |
| `migrate-get` | Exports canonical SQL without connecting to a database. |
| `version` | Prints the CLI version; `--version` works too. |
Use `--target-version N` to stop at a version, `--max-steps N` to limit the count,
and `--dry-run --show-sql` to inspect a planned change. On `migrate-down`, target
version `0` explicitly removes the entire migration line. A zero `--max-steps`
uses the command's default: all pending up migrations or one down migration.
```sh
river-java migrate-down --max-steps 2 --dry-run --show-sql
river-java migrate-up --target-version 8
river-java migrate-get --version 3 --up > river_3.up.sql
river-java migrate-get --driver sqlite --all --up > river_sqlite.up.sql
```
SQL export defaults to Postgres without a database URL. Use `--driver sqlite`
for SQLite, or select the dialect through the URL. Export accepts comma-separated
`--version` values or `--all`; `--exclude-version 1` excludes migration history
setup when exporting for another migration framework. Exit codes are `0` for
success, `1` for an operation failure, and `2` for invalid arguments.
The [migration history](https://riverqueue.com/docs/migrations) is shared with
River clients in other languages. Use the CLI version matching your Java library. The Java
API remains available for embedded use:
```java
var result = new Migrator(database).migrate();
System.out.println("Applied migrations: " + result.applied());
var preview = new Migrator(database).migrate(Migrator.Direction.DOWN,
Migrator.Options.defaults().maxSteps(2).dryRun(true));
```
### Running with Maven and Java
In an empty directory, create this consumer POM and download the runtime JARs:
```sh
cat > pom.xml <<'EOF'
4.0.0
localriver-cli-install1
riverhttps://riverqueue.com/maven
com.riverqueueriver-cli0.4.1
EOF
mvn --batch-mode --no-transfer-progress \
org.apache.maven.plugins:maven-dependency-plugin:3.11.0:copy-dependencies \
-DincludeScope=runtime
java --enable-native-access=ALL-UNNAMED -cp 'target/dependency/*' \
com.riverqueue.cli.MigrationCli --help
```
Replace `--help` with any migration command above. Copy the entire
`target/dependency` directory into a deployment image and adjust the classpath to
its location. Running it needs only Java; Maven and network access are needed
when downloading the dependencies.
## Transactional enqueueing
[Enqueue in the application's transaction](https://riverqueue.com/docs/transactional-enqueueing)
so the job and application writes commit or roll back together. Pass a JDBC
connection with auto-commit disabled. River uses savepoints and never commits,
rolls back the outer transaction, or closes that connection. Insert hooks and
middleware run inside the same transaction.
```java
try (var connection = applicationDataSource.getConnection()) {
connection.setAutoCommit(false);
try {
accounts.create(connection, account);
client.insert(connection, email, new SendEmail(account.email(), "Welcome"));
connection.commit();
} catch (Exception failure) {
connection.rollback();
throw failure;
}
}
```
`client.transaction(connection -> ...)` manages a new transaction for River-owned
operations. `client.transaction(existingConnection, connection -> ...)` groups
multiple operations under one savepoint in an existing transaction. Neither
`Client` nor `Database` needs closing; the application owns its pool. Workers should be [idempotent](https://riverqueue.com/docs/reliable-workers):
process failure can cause an attempt to run again after its external effects
have succeeded.
## Inserting many jobs
[Bulk insertion](https://riverqueue.com/docs/inserting-many-jobs) inserts a list atomically.
For an existing JDBC transaction, use the connection-first overload of either
form below. Homogeneous batches take a common job type. Mixed batches use
submissions with their own kind and options. Both return insertion results
containing the persisted `Job` values.
```java
var inserted = client.insertMany(email, List.of(
new SendEmail("one@example.com", "Welcome"),
new SendEmail("two@example.com", "Welcome")));
record GenerateReport(long accountId) {}
var report = JobType.of("generate_report", GenerateReport.class);
var mixed = client.insertMany(List.of(
email.submission(new SendEmail("one@example.com", "Welcome")),
report.submission(new GenerateReport(42), InsertOptions.builder().queue("reports").build())));
```
## Reading typed jobs
Job operations live on `client.jobs()`, alongside queue operations on
`client.queues()`. Use `jobs().get`, `list`, `cancel`, `delete`, `deleteMany`,
`retry`, `complete`, and `update`. Insertions remain `client.insert` and
`client.insertMany`. Connection-first overloads use an existing transaction;
`jobs().complete` always requires one.
`client.jobs().get(id)` returns `Job` because an ID does not identify a Java
argument class. Supply a job type when it is known:
```java
Job job = client.jobs().get(jobId, email);
System.out.println(job.args().address());
```
Typed retrieval checks the kind and decodes the arguments.
`context.complete(connection)` also retains its `Job` argument type.
Insertion results contain `Job` because uniqueness can return an
existing job with another kind or argument schema. The returned arguments are
the persisted values, including any additional fields written by another language.
See the [API review](API.md) for the full application surface and prerelease API changes.
Lists default to ascending job ID order. Keep the filters and order
unchanged when continuing from a page's cursor:
```java
var query = JobQuery.builder().kinds("send_email").limit(50).build();
var first = client.jobs().list(query);
if (!first.jobs().isEmpty()) {
var next = client.jobs().list(query.after(first.cursor()));
}
```
Use `order(JobQuery.Order.TIME)` for ordering by the timestamp appropriate to the
selected state, or `SCHEDULED_AT` or `FINALIZED_AT` for an explicit timestamp.
## Job retries
A thrown exception triggers [retries](https://riverqueue.com/docs/job-retries)
until `maxAttempts` is exhausted, when the job becomes discarded. The default
policy uses River's quartic backoff with jitter. Configure a different policy
on the client builder, or explicitly retry an existing job with `client.jobs().retry(id)`.
An explicit retry that updates a job notifies its queue after commit. Use
`client.jobs().retry(connection, id)` to make the retry part of an existing transaction.
A retry policy receives the full job snapshot before the current failure is
appended to `errors`; use `job.errors().size() + 1` to include that failure.
It runs only when another attempt is possible. Return a nonnegative `Duration`;
if the policy throws, returns null or a negative delay, or overflows the retry
time, River reports the problem and uses its default backoff.
```java
var retryingEmail = email.withDefaults(InsertOptions.builder().maxAttempts(10).build());
var clientBuilder = Client.builder(database)
.queue(Client.QUEUE_DEFAULT, 10)
.retryPolicy(job -> Duration.ofSeconds(Math.min(300, 5L * (job.errors().size() + 1))))
.worker(retryingEmail, context ->
mailer.send(context.args().address(), context.args().subject()));
client.insert(retryingEmail, new SendEmail("hello@example.com", "Welcome"));
```
Call `clientBuilder.build()` to create the configured client, then call its
`start()` method and keep the returned handle open as in the first example.
Job-type defaults apply when inserting through that `JobType`; another producer
must set its own compatible options.
## Features
These sections follow the non-Pro entries in the River documentation's
[Features sidebar](https://riverqueue.com/docs). Snippets are independent and
reuse `client` and `database` from the quick start, with imports from
`com.riverqueue`, `java.time`, and `java.util`. Handler examples configure a builder;
call `build()` after registering your handlers, then start that client. In runtime
examples, `run` is the `RunHandle` returned by `client.start()`. `mailer`, `accounts`, and `deliveries`
are application services, `applicationDataSource` is your JDBC connection pool,
`application.awaitStop()` waits for your service to stop, and `jobId` is an
existing job's ID.
```java
var email = JobType.of("send_email", SendEmail.class);
var clientBuilder = Client.builder(database).queue(Client.QUEUE_DEFAULT, 10);
```
### Cancelling jobs
[Cancel](https://riverqueue.com/docs/cancelling-jobs) an enqueued or running job
with `client.jobs().cancel(id)`. Running attempts receive a cooperative cancellation
signal. A handler can cancel itself permanently with `context.cancel(reason)`;
this ends the attempt without further retries.
```java
client.jobs().cancel(jobId);
clientBuilder.worker(email, context -> {
context.checkCancelled();
if (context.args().address().isBlank()) context.cancel("Missing address");
mailer.send(context.args().address(), context.args().subject());
});
```
Long-running handlers should check cancellation between operations and use
interruptible I/O. `context.awaitCancellation()` waits for the signal.
A normal return reports success even if cancellation or a timeout was
requested. Call `context.checkCancelled()` when abandoning unfinished work.
### Worker timeouts
`Client.Builder.jobTimeout` sets the default attempt timeout. Override
`Handler.timeout(job)` for a particular worker; the callback receives typed
arguments and can choose a duration per job:
```java
clientBuilder.worker(email, new Workers.Handler() {
@Override
public Duration timeout(Job job) {
return Duration.ofMinutes(5);
}
@Override
public void work(WorkContext context) {
mailer.send(context.args().address(), context.args().subject());
}
});
```
Returning `null` or `Duration.ZERO` inherits the runtime default, as lambda
handlers do. A negative duration disables the timeout. The callback also runs when
the leader considers abandoned jobs for rescue, so keep it thread-safe and free of
side effects. Rescue respects longer worker deadlines and disabled timeouts.
### Getting the client within workers
[`context.client()`](https://riverqueue.com/docs/context-client) gives a handler
its client, including configured hooks and middleware. Use its transaction overloads when
enqueueing follow-up work that must commit with other writes or job completion.
```java
record Welcome(String address) {}
var welcome = JobType.of("welcome", Welcome.class);
clientBuilder.worker(welcome, context ->
context.client().insert(email, new SendEmail(context.args().address(), "Welcome")));
```
### Error and panic handling
Java exceptions and uncaught `Error`s are handled as failed attempts; River
persists failures and retries according to policy. For
[application error reporting](https://riverqueue.com/docs/error-handling), attach
a `HookWorkEnd` hook. `Client.Builder.errorHandler` separately receives
runtime failures, such as database or subscriber errors.
Failures in observers or event subscribers are reported without changing the
job's outcome or preventing other callbacks from running. If the runtime error
handler itself throws, River logs both failures and continues.
```java
HookWorkEnd reportFailure = (context, failure) -> {
if (failure != null) {
System.getLogger("jobs").log(System.Logger.Level.ERROR,
"Job " + context.job().id() + " failed", failure);
}
return failure;
};
var clientBuilder = Client.builder(database).plugins(reportFailure)
.queue(Client.QUEUE_DEFAULT, 10)
.errorHandler(failure ->
System.getLogger("river").log(System.Logger.Level.ERROR, "Runtime failure", failure))
.worker(email, context -> mailer.send(context.args().address(), context.args().subject()));
```
Hooks also see the control exceptions used for snoozing and cancellation. Keep
reporting hooks fast and avoid throwing from them.
### Plugins, hooks, and middleware
Use `client.withPlugins(...)` to install hooks and middleware together. `Plugin`
is their common marker interface: `Hook` and `Middleware` both extend it. A
plugin automatically activates every operation-specific interface it implements.
Hooks observe individual lifecycle stages through `HookInsertBegin`,
`HookWorkBegin`, `HookWorkEnd`, and `HookPeriodicJobsStart`. Middleware wraps an
operation with a `next` callback through `JobInsertMiddleware` and
`WorkerMiddleware`. Each is a functional interface for lambdas or method
references. For example, individual callbacks can be installed together:
```java
JobInsertMiddleware logInsert = (connection, submissions, next) -> {
var results = next.call();
System.getLogger("jobs").log(System.Logger.Level.DEBUG,
"Inserted " + results.size() + " jobs");
return results;
};
WorkerMiddleware timeWork = (context, next) -> {
long started = System.nanoTime();
try {
next.run();
} finally {
System.getLogger("jobs").log(System.Logger.Level.DEBUG,
"Job " + context.job().id() + " took " + (System.nanoTime() - started) + " ns");
}
};
var instrumentedClient = client.withPlugins(reportFailure, logInsert, timeWork);
```
A reusable plugin can implement multiple interfaces on one class:
```java
final class JobInstrumentation implements HookWorkEnd, WorkerMiddleware {
@Override
public void work(WorkContext> context, WorkContext.Step next) throws Exception {
System.getLogger("jobs").log(System.Logger.Level.DEBUG,
"Starting job " + context.job().id());
next.run();
}
@Override
public Throwable workEnd(WorkContext> context, Throwable failure) {
if (failure != null) {
System.getLogger("jobs").log(System.Logger.Level.ERROR,
"Job " + context.job().id() + " failed", failure);
}
return failure;
}
}
var instrumentedClient = client.withPlugins(new JobInstrumentation());
```
Use `withHooks(...)` or `withMiddleware(...)` when only that side of an
implementation should be activated. All three registration methods return a new
client and append to their respective lists. Use the returned client for insertion
and worker configuration. Instances can run concurrently and must protect shared
mutable state.
As in Go, plugins run first, followed by separately registered hooks or middleware,
regardless of which registration method was called first. Each list preserves its
registration order. Repeated registrations are retained, so registering the same
instance twice invokes it twice for each applicable phase.
Hooks run in registration order inside the innermost middleware. Middleware runs
in registration order before `next` and unwinds in reverse order afterward.
Insertion middleware runs once per batch, including a one-element batch for a
single insertion; insert hooks run once per job. Middleware receives an immutable
list of submissions with the caller's arguments and option overrides. Insert
hooks and middleware run in the insertion's transaction, and a failure anywhere
rolls back the insertion, even after `next` returns.
Work hooks and middleware receive decoded arguments. A work-begin failure skips
the handler and work-end hooks. Work-end hooks receive the handler's exception
or `Error`, or `null` for success, and return the outcome passed to the next hook.
Return the received failure to preserve it, a different failure to replace it,
or `null` to report success. A thrown exception skips remaining work-end hooks.
The internal `Pilot` interface is a River Pro storage integration point, separate
from application plugins.
### Job-persisted logging
[Job logs](https://riverqueue.com/docs/job-logging) live in `river:log` metadata
as an array of `{attempt, log}` objects. Java has no bundled job-logging
middleware yet. You can explicitly write that shared format; this
example appends a fixed message and retains the last ten attempt entries.
```java
clientBuilder.worker(email, context -> {
var logs = new ArrayList