← Java

Java · 22 / 24

Transactions and concurrent changes

Prevent lost updates with a version condition and verify rollback.

  • Large
  • Advanced
  • 90 min

Prerequisites: JDBC, SQLite and local transactions, Understand PostgreSQL, JPA and Flyway

In this tutorial
  1. Read the domain contract
  2. Start an isolated environment
  3. Verify success and failure
  4. Make a regression visible
  5. Extend the contract
  6. Explain the solution and its limits
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

JDK 21, Maven 3.9 or newer, Docker. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

verify.py starts PostgreSQL itself. Sample data exists only in this temporary test container.

Verified on 2026-10-20 on Linux x86_64. Two separate connections read the same version. Exactly one update wins. A second test checks rollback. A new transaction must not see a partial effect from the failed operation.

Two users may have read the same confirmed state. A later save must not silently overwrite the first change. UPDATE therefore includes the previously read version. One affected row means success, while zero means conflict. The test uses two real PostgreSQL connections and checks final contents.

Package contents and individual files

01Read the domain contract

A version belongs to the record that was read. The UPDATE accepts only that version and increments it atomically. Zero affected rows reveal a concurrent write. The caller must reload or explain the conflict.

src/main/java/tutorial/VersionedStore.java · javaOpen file
package tutorial;

import java.sql.*;

public class VersionedStore {

  public static Connection connect() throws SQLException {
    return DriverManager.getConnection(
      System.getenv("LEARNING_DATABASE_URL"),
      "learning",
      "learning"
    );
  }

  public static int update(Connection c, String name, int expected)
    throws SQLException {
    try (
      var s = c.prepareStatement(
        "UPDATE vehicles SET name=?,version=version+1 WHERE id=1 AND version=?"
      )
    ) {
      s.setString(1, name);
      s.setInt(2, expected);
      return s.executeUpdate();
    }
  }
}

02Start an isolated environment

Java 21 is the language baseline. Maven resolves dependencies from the POM. verify.py creates its own PostgreSQL instance on an available local port and removes only that container after testing.

pom.xml · xmlOpen file
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>4.1.0</version></parent>
<groupId>learning</groupId><artifactId>tutorial</artifactId><version>1.0</version>
<properties><java.version>21</java.version></properties>
<dependencies>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId></dependency>
</dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

03Verify success and failure

Two separate connections read the same version. Exactly one update wins. A second test checks rollback. A new transaction must not see a partial effect from the failed operation.

src/test/java/tutorial/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class LessonTest {

  @Test
  void staleWriteCannotOverwriteAndRollbackPreservesState() throws Exception {
    try (var a = VersionedStore.connect(); var b = VersionedStore.connect()) {
      try (var s = a.createStatement()) {
        s.execute(
          "CREATE TABLE vehicles(id INT PRIMARY KEY,name TEXT NOT NULL,version INT NOT NULL)"
        );
        s.execute("INSERT INTO vehicles VALUES(1,'Original',1)");
      }
      a.setAutoCommit(false);
      b.setAutoCommit(false);
      assertEquals(1, VersionedStore.update(a, "First", 1));
      a.commit();
      assertEquals(0, VersionedStore.update(b, "Stale", 1));
      b.rollback();
      assertEquals(1, VersionedStore.update(a, "Temporary", 2));
      a.rollback();
      try (
        var s = b.createStatement();
        var r = s.executeQuery("SELECT name,version FROM vehicles WHERE id=1")
      ) {
        assertTrue(r.next());
        assertEquals("First", r.getString(1));
        assertEquals(2, r.getInt(2));
      }
      b.rollback();
    }
  }
}

Run / check

python3 verify.py
Expected result

Two separate connections read the same version. Exactly one update wins. A second test checks rollback. A new transaction must not see a partial effect from the failed operation.

04Make a regression visible

Change a domain expectation and rerun the test. Maven must report failure. A skipped database test is not evidence. Restore the correct expectation afterwards.

05Extend the contract

Explicitly retry the discarded change using the current version.

06Explain the solution and its limits

A new user decision with version 2 can succeed and increment to version 3. Blind automatic retry could overwrite a domain decision. The solution checks affected rows and new contents. Copy solution/LessonTest.java over the test file and repeat the same verification.

Expected result

All tests pass, including the additional solution expectation.

Your exercise

Explicitly retry the discarded change using the current version.

Show the solution and explanation

A new user decision with version 2 can succeed and increment to version 3. Blind automatic retry could overwrite a domain decision. The solution checks affected rows and new contents.

solution/LessonTest.java · javaOpen file
package tutorial;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class LessonTest {

  @Test
  void staleWriteCannotOverwriteAndRollbackPreservesState() throws Exception {
    try (var a = VersionedStore.connect(); var b = VersionedStore.connect()) {
      try (var s = a.createStatement()) {
        s.execute(
          "CREATE TABLE vehicles(id INT PRIMARY KEY,name TEXT NOT NULL,version INT NOT NULL)"
        );
        s.execute("INSERT INTO vehicles VALUES(1,'Original',1)");
      }
      a.setAutoCommit(false);
      b.setAutoCommit(false);
      assertEquals(1, VersionedStore.update(a, "First", 1));
      a.commit();
      assertEquals(0, VersionedStore.update(b, "Stale", 1));
      b.rollback();
      assertEquals(1, VersionedStore.update(a, "Temporary", 2));
      a.rollback();
      try (
        var s = b.createStatement();
        var r = s.executeQuery("SELECT name,version FROM vehicles WHERE id=1")
      ) {
        assertTrue(r.next());
        assertEquals("First", r.getString(1));
        assertEquals(2, r.getInt(2));
      }
      b.rollback();
      assertEquals(1, VersionedStore.update(b, "Reviewed", 2));
      b.commit();
      try (
        var s = b.createStatement();
        var r = s.executeQuery("SELECT name,version FROM vehicles WHERE id=1")
      ) {
        assertTrue(r.next());
        assertEquals("Reviewed", r.getString(1));
        assertEquals(3, r.getInt(2));
      }
    }
  }
}

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.