Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions examples/ideas-board/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Concurrent Ideas Board — pure-Java example

The pure-Java twin of the Spring and .NET fundamentals demos. It shows the
library's hero feature: **automatic retry on serialization conflicts (SQLSTATE
40001)**. Many threads upvote the same idea; without retry votes are lost, with
`Crdb.tx(...)` every vote lands.

Pinned to `cockroachdb-java-library` **0.1.2** (anonymous Maven Pages feed).

## What it shows

- `upvoteWithoutRetry(id)` — a plain SERIALIZABLE read-modify-write. Under
contention CockroachDB raises 40001 and the lost conflicts never recover.
- `upvote(id)` — the same work wrapped in `Crdb.tx(ds, conn -> …)`, which runs
SERIALIZABLE and replays the whole transaction on each 40001. All votes land.

## Prerequisites

- Java 25 (`sdk use java 25.0.2-graalce`) and Gradle 9.x.
- For `gradle run`: a reachable CockroachDB. Start one locally:
```
cockroach start-single-node --insecure --listen-addr=localhost:26257
```
Override the URL with `JDBC_URL` (default
`jdbc:postgresql://localhost:26257/defaultdb?sslmode=disable&user=root`).
- For `gradle test`: Docker only — the test spins up CockroachDB via
Testcontainers (`CockroachHarness`). No local cluster needed.

## Run

```bash
# Prove it under contention (Testcontainers; Docker must be up):
gradle test

# Watch lost votes vs. retried votes against a running cluster:
gradle run
```

`gradle run` prints both outcomes, e.g.:

```
WITHOUT retry (plain) successes=41 failures=19 votes=41/60
WITH Crdb.tx retry successes=60 failures=0 votes=60/60
```

## The proof

`IdeaServiceConcurrencyTest` runs 3 threads × 20 iterations (60 upvotes) on one
idea via the testing module's `ConcurrencyRunner`, and asserts:

- the retry path lands **exactly 60** votes with **zero** failures;
- the plain path does **not** reliably reach 60 (votes lost or failures raised).
85 changes: 85 additions & 0 deletions examples/ideas-board/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
plugins {
id 'application'
id 'java'
}

group = 'com.cockroachlabs.ideas'
version = '0.1.0'

java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}

application {
mainClass = 'com.cockroachlabs.ideas.Main'
}

// tag::repo-maven[]
repositories {
mavenCentral()
// Anonymous, no-token CockroachDB Java library Maven feed (GitHub Pages).
maven {
name = 'cockroachdb-java-library'
url = 'https://cockroachlabs.github.io/cockroachdb-java-library/maven/'
}
}
// end::repo-maven[]

// tag::deps[]
dependencies {
// The pure-Java library core: Crdb.tx(...) retry entry point, @FollowerRead,
// Crdb.enhance(...). Pinned 0.1.2.
implementation 'com.cockroachlabs:cockroachdb-java-library-core:0.1.2'

// Metrics module: CrdbMetrics facade + InMemoryMetricsRecorder, counting
// transactions and observe-bus retry events.
implementation 'com.cockroachlabs:cockroachdb-java-library-metrics:0.1.2'

// CDC module: CdcEventHandler, CdcEventDecoder, ChangefeedHandlerRegistry for
// consuming CockroachDB changefeed webhook deliveries.
implementation 'com.cockroachlabs:cockroachdb-java-library-cdc:0.1.2'

// AI module: VectorStore + VectorDocument + DistanceMetric over CockroachDB's
// native VECTOR type, for semantic / similarity search.
implementation 'com.cockroachlabs:cockroachdb-java-library-ai:0.1.2'

// A JDBC driver + DataSource for plain read-modify-write DAO code.
implementation 'org.postgresql:postgresql:42.7.14'

// Testing module: Testcontainers CockroachDB harness + concurrency runner.
// Declared as implementation (not test-only) so Main can drive the same
// ConcurrencyRunner the test uses; it stays available to the test too.
implementation 'com.cockroachlabs:cockroachdb-java-library-testing:0.1.2'

// JUnit 6 (matches the library's parent junitVersion 6.1.3).
testImplementation 'org.junit.jupiter:junit-jupiter:6.1.3'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

// Mockito for the fast, no-DB unit test: mocks DataSource / Connection /
// IdeaRepository so IdeaService logic is verified without Docker. 5.24.0
// bundles a ByteBuddy that supports Java 25, and its inline mock maker
// (default in Mockito 5) can mock the final IdeaRepository class.
testImplementation 'org.mockito:mockito-core:5.24.0'
}
// end::deps[]

// Mockito's inline mock maker needs a Java agent. Self-attach works today but
// is deprecated on modern JDKs, so load mockito-core explicitly as an agent
// (the documented, future-proof setup) to keep the unit test clean on Java 25.
configurations {
mockitoAgent
}
dependencies {
mockitoAgent('org.mockito:mockito-core:5.24.0') { transitive = false }
}

tasks.named('test') {
useJUnitPlatform()
jvmArgs "-javaagent:${configurations.mockitoAgent.asPath}"
testLogging {
events 'passed', 'skipped', 'failed'
showStandardStreams = true
}
}
1 change: 1 addition & 0 deletions examples/ideas-board/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'ideas-board'
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.cockroachlabs.ideas;

import java.util.UUID;

// tag::entity[]
/**
* An idea on the board. {@code votes} is the hotly-contended column: many
* upvotes race to increment the same row, which is exactly where CockroachDB's
* SERIALIZABLE isolation raises 40001 and the library's retry earns its keep.
*/
public record Idea(UUID id, String text, int votes) {
}
// end::entity[]
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.cockroachlabs.ideas;

import com.cockroachlabs.crdb.cdc.CdcEvent;
import com.cockroachlabs.crdb.cdc.CdcEventHandler;
import com.cockroachlabs.crdb.cdc.Operation;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.CopyOnWriteArrayList;

// tag::cdc-handler[]
/**
* A {@link CdcEventHandler} for the {@code idea} table. CockroachDB's changefeed
* webhook delivers batches of decoded {@link CdcEvent}s; this handler turns each
* insert/update into an {@link Idea} and tracks deletes, so an app can mirror the
* ideas board into a cache, search index, or audit log as rows change.
*
* <p>Thread-safe: a changefeed webhook can deliver batches concurrently.
*/
public final class IdeaChangefeedHandler implements CdcEventHandler {

/** The table this handler is registered for. */
public static final String TABLE = "idea";

private final List<Idea> handled = new CopyOnWriteArrayList<>();
private final AtomicInteger deletes = new AtomicInteger();

@Override
public void handle(List<CdcEvent> events) {
for (CdcEvent event : events) {
if (event.operation() == Operation.DELETE) {
deletes.incrementAndGet(); // after-image is null on a delete
continue;
}
handled.add(toIdea(event.after()));
}
}

/** Project a changefeed {@code after} image onto an {@link Idea}. */
static Idea toIdea(Map<String, Object> after) {
return new Idea(
UUID.fromString(String.valueOf(after.get("id"))),
String.valueOf(after.get("text")),
((Number) after.get("votes")).intValue()); // JSON numbers decode as Number
}

/** Ideas seen so far from insert/update events, in arrival order. */
public List<Idea> handled() {
return List.copyOf(handled);
}

/** Count of delete events seen. */
public int deletes() {
return deletes.get();
}
}
// end::cdc-handler[]
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.cockroachlabs.ideas;

import com.cockroachlabs.crdb.ai.VectorDocument;

import java.util.Map;

// tag::vector-entity[]
/**
* An idea with a small fixed-dimension embedding, stored in a CockroachDB native
* {@code VECTOR} column so similar ideas can be found by vector distance.
*
* <p>The embedding here is a deterministic {@code float[3]} supplied by the caller
* (no model): that keeps the semantic-search integration test reproducible on a
* single node. In a real app the vector would come from an {@code EmbeddingProvider}
* (OpenAI, Ollama, a local model) of whatever width the column declares.
*/
public record IdeaDoc(String id, String text, float[] embedding) {

/** Embedding width; must match the {@code VECTOR(DIMENSIONS)} column. */
public static final int DIMENSIONS = 3;

/**
* Map to the AI module's {@link VectorDocument}, carrying the precomputed
* embedding (non-null, so the store never consults an embedding model).
*/
public VectorDocument toVectorDocument() {
return new VectorDocument(id, text, embedding, Map.of());
}
}
// end::vector-entity[]
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.cockroachlabs.ideas;

import com.cockroachlabs.crdb.Crdb;
import com.cockroachlabs.crdb.annotations.FollowerRead;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

// tag::follower-read[]
/**
* Leaderboard reads served from a follower via the library's {@code @FollowerRead}
* API. The annotated method runs through a {@link Crdb#enhance enhanced} proxy,
* which binds the follower-read staleness into the call context; the
* {@code Crdb.tx} transaction then emits
* {@code SET TRANSACTION AS OF SYSTEM TIME follower_read_timestamp()} as its first
* statement, so the leaderboard query runs against a slightly-stale snapshot the
* nearest replica can serve — no leaseholder round-trip.
*
* <p>This is an interface (plus a factory and a package-private impl) so
* {@code Crdb.enhance} uses the JDK-dynamic-proxy strategy: the enhanced object is
* the interface type and delegates to the original instance, which is the exact
* idiom the library's own integration test uses for an annotated, DataSource-backed
* service.
*/
public interface IdeaReadService {

/**
* The top ideas by vote count, read from a follower at
* {@code follower_read_timestamp()} (about 4.8s stale). Because the read is
* historical, freshly-inserted rows become visible only once wall-clock time
* advances past the staleness window.
*/
@FollowerRead
List<Idea> topIdeas(int limit);

/** Build a follower-read-enabled view over {@code ds}. */
static IdeaReadService create(DataSource ds) {
return Crdb.enhance((IdeaReadService) new Impl(ds));
}

/** JDBC implementation; the {@code @FollowerRead} on the concrete method is what the proxy reads. */
final class Impl implements IdeaReadService {

private final DataSource ds;

Impl(DataSource ds) {
this.ds = ds;
}

@Override
@FollowerRead
public List<Idea> topIdeas(int limit) {
// Crdb.tx picks up the follower-read staleness bound by the proxy and
// applies SET TRANSACTION AS OF SYSTEM TIME before this query runs.
return Crdb.tx(ds, c -> {
try (PreparedStatement ps = c.prepareStatement(
"SELECT id, text, votes FROM idea ORDER BY votes DESC, text ASC LIMIT ?")) {
ps.setInt(1, limit);
try (ResultSet rs = ps.executeQuery()) {
List<Idea> out = new ArrayList<>();
while (rs.next()) {
out.add(new Idea(
(UUID) rs.getObject("id"),
rs.getString("text"),
rs.getInt("votes")));
}
return out;
}
}
});
}
}
}
// end::follower-read[]
Loading
Loading