Skip to content
This repository was archived by the owner on Mar 26, 2026. It is now read-only.

Commit ca243d1

Browse files
authored
docs: add samples for transaction isolation level (#2030)
* docs: add samples for transaction isolation level * docs: update README and latency guide
1 parent f73bd27 commit ca243d1

5 files changed

Lines changed: 272 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ See [Supported Connection Properties](documentation/connection_properties.md) fo
109109
supported connection properties.
110110

111111
#### Commonly Used Properties
112+
- default_isolation_level (String): Spanner supports isolation levels REPEATABLE_READ or SERIALIZABLE. SERIALIZABLE is the default. Using isolation level REPEATABLE_READ improves performance by reducing the amount of locks that are taken by transactions that execute a large number of queries in read/write transactions. See https://cloud.google.com/spanner/docs/isolation-levels for more information on the supported isolation levels in Spanner.
112113
- credentials (String): URL for the credentials file to use for the connection. If you do not specify any credentials at all, the default credentials of the environment as returned by `GoogleCredentials#getApplicationDefault()` is used. Example: `jdbc:cloudspanner:/projects/my-project/instances/my-instance/databases/my-db;credentials=/path/to/credentials.json`
113114
- autocommit (boolean): Sets the initial autocommit mode for the connection. Default is true.
114115
- readonly (boolean): Sets the initial readonly mode for the connection. Default is false.

documentation/latency-debugging-guide.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,43 @@ queries and transactions and to determine whether transactions or requests are b
55
addition, all metrics described in [Latency points in a Spanner request](https://cloud.google.com/spanner/docs/latency-points)
66
are also collected by the JDBC driver and can be used for debugging.
77

8+
## Isolation Level
9+
10+
A common reason for high latency in read/write transactions is lock contention. Spanner by default
11+
uses isolation level `SERIALIZABLE`. This causes all queries in read/write transactions to take
12+
locks for all rows that are scanned by a query. Using isolation level `REPEATABLE_READ` reduces the
13+
number of locks that are taken during a read/write transaction, and can significantly improve
14+
performance for applications that execute many and/or large queries in read/write transactions.
15+
16+
Enable isolation level `REPEATABLE_READ` by default for all transactions that are executed by the
17+
JDBC driver by setting the `default_isolation_level` connection property like this in the connection
18+
URL:
19+
20+
```java
21+
String projectId = "my-project";
22+
String instanceId = "my-instance";
23+
String databaseId = "my-database";
24+
String isolationLevel = "REPEATABLE_READ";
25+
26+
try (Connection connection =
27+
DriverManager.getConnection(
28+
String.format(
29+
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s?default_isolation_level=%s",
30+
projectId, instanceId, databaseId, isolationLevel))) {
31+
try (Statement statement = connection.createStatement()) {
32+
try (ResultSet rs = statement.executeQuery("SELECT CURRENT_TIMESTAMP()")) {
33+
while (rs.next()) {
34+
System.out.printf(
35+
"Connected to Cloud Spanner at [%s]%n", rs.getTimestamp(1).toString());
36+
}
37+
}
38+
}
39+
}
40+
```
41+
42+
See https://cloud.google.com/spanner/docs/isolation-levels for more information on the supported
43+
isolation levels in Spanner.
44+
845
## Configuration
946

1047
You can configure the OpenTelemetry instance that should be used in two ways:
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.spanner.jdbc;
18+
19+
import java.sql.Connection;
20+
import java.sql.DriverManager;
21+
import java.sql.PreparedStatement;
22+
import java.sql.ResultSet;
23+
import java.sql.SQLException;
24+
import java.util.Properties;
25+
26+
final class IsolationLevel {
27+
28+
static void isolationLevel(
29+
final String project,
30+
final String instance,
31+
final String database,
32+
final Properties properties)
33+
throws SQLException {
34+
String url = String.format(
35+
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
36+
project, instance, database);
37+
try (Connection connection = DriverManager.getConnection(url, properties)) {
38+
connection.setAutoCommit(false);
39+
40+
// Spanner supports setting the isolation level to:
41+
// 1. TRANSACTION_SERIALIZABLE (this is the default)
42+
// 2. TRANSACTION_REPEATABLE_READ
43+
44+
// The following line sets the default isolation level that will be used
45+
// for all read/write transactions on this connection.
46+
connection.setTransactionIsolation(
47+
Connection.TRANSACTION_REPEATABLE_READ);
48+
49+
// This query will not take any locks when using
50+
// isolation level repeatable read.
51+
try (ResultSet resultSet = connection
52+
.createStatement()
53+
.executeQuery("SELECT SingerId, Active "
54+
+ "FROM Singers "
55+
+ "ORDER BY LastName")) {
56+
while (resultSet.next()) {
57+
try (PreparedStatement statement = connection.prepareStatement(
58+
"INSERT OR UPDATE INTO SingerHistory "
59+
+ "(SingerId, Active, CreatedAt) "
60+
+ "VALUES (?, ?, CURRENT_TIMESTAMP)")) {
61+
statement.setLong(1, resultSet.getLong(1));
62+
statement.setBoolean(2, resultSet.getBoolean(2));
63+
statement.executeUpdate();
64+
}
65+
}
66+
}
67+
connection.commit();
68+
}
69+
}
70+
71+
private IsolationLevel() {
72+
}
73+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* Copyright 2025 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.example.spanner.jdbc;
18+
19+
import static com.example.spanner.jdbc.IsolationLevel.isolationLevel;
20+
import static org.junit.Assume.assumeTrue;
21+
22+
import java.sql.Connection;
23+
import java.sql.DriverManager;
24+
import java.sql.SQLException;
25+
import java.sql.Statement;
26+
import java.util.Properties;
27+
import org.junit.AfterClass;
28+
import org.junit.BeforeClass;
29+
import org.junit.Test;
30+
import org.junit.runner.RunWith;
31+
import org.junit.runners.JUnit4;
32+
import org.testcontainers.DockerClientFactory;
33+
import org.testcontainers.containers.GenericContainer;
34+
import org.testcontainers.containers.wait.strategy.Wait;
35+
import org.testcontainers.images.PullPolicy;
36+
import org.testcontainers.utility.DockerImageName;
37+
38+
@RunWith(JUnit4.class)
39+
public class IsolationLevelTest {
40+
41+
private static GenericContainer<?> emulator;
42+
43+
private static final String PROJECT = "emulator-project";
44+
private static final String INSTANCE = "my-instance";
45+
private static final String DATABASE = "my-database";
46+
private static final Properties PROPERTIES = new Properties();
47+
48+
@BeforeClass
49+
public static void setupEmulator() throws Exception {
50+
assumeTrue("This test requires Docker", DockerClientFactory.instance().isDockerAvailable());
51+
52+
emulator =
53+
new GenericContainer<>(DockerImageName.parse("gcr.io/cloud-spanner-emulator/emulator"));
54+
emulator.withImagePullPolicy(PullPolicy.alwaysPull());
55+
emulator.addExposedPort(9010);
56+
emulator.setWaitStrategy(Wait.forListeningPorts(9010));
57+
emulator.start();
58+
59+
PROPERTIES.setProperty("endpoint",
60+
String.format("localhost:%d", emulator.getMappedPort(9010)));
61+
PROPERTIES.setProperty("autoConfigEmulator", "true");
62+
63+
String url = String.format(
64+
"jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s",
65+
PROJECT, INSTANCE, DATABASE);
66+
try (Connection connection = DriverManager.getConnection(url, PROPERTIES)) {
67+
try (Statement statement = connection.createStatement()) {
68+
statement.addBatch(
69+
"CREATE TABLE Singers ("
70+
+ "SingerId INT64 PRIMARY KEY, "
71+
+ "FirstName STRING(MAX), "
72+
+ "LastName STRING(MAX), "
73+
+ "Active BOOL)");
74+
statement.addBatch(
75+
"CREATE TABLE SingerHistory ("
76+
+ "SingerId INT64, "
77+
+ "Active BOOL, "
78+
+ "CreatedAt TIMESTAMP) "
79+
+ "PRIMARY KEY (SingerId, CreatedAt)");
80+
statement.executeBatch();
81+
}
82+
}
83+
}
84+
85+
@AfterClass
86+
public static void stopEmulator() {
87+
if (emulator != null) {
88+
emulator.stop();
89+
}
90+
}
91+
92+
@Test
93+
public void testIsolationLevel() throws SQLException {
94+
isolationLevel("emulator-project", "my-instance", "my-database", PROPERTIES);
95+
}
96+
97+
}

src/test/java/com/google/cloud/spanner/jdbc/JdbcTransactionOptionsTest.java

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,15 @@
2727
import com.google.cloud.spanner.connection.AbstractMockServerTest;
2828
import com.google.cloud.spanner.connection.SpannerPool;
2929
import com.google.spanner.v1.CommitRequest;
30+
import com.google.spanner.v1.ExecuteSqlRequest;
31+
import com.google.spanner.v1.TransactionOptions.IsolationLevel;
32+
import java.sql.Connection;
3033
import java.sql.DriverManager;
3134
import java.sql.ResultSet;
3235
import java.sql.SQLException;
3336
import java.time.Duration;
37+
import java.util.Arrays;
38+
import java.util.stream.Collectors;
3439
import org.junit.After;
3540
import org.junit.Test;
3641
import org.junit.runner.RunWith;
@@ -138,4 +143,63 @@ public void testMaxCommitDelay() throws SQLException {
138143
assertEquals(Duration.ofMillis(50).toNanos(), request.getMaxCommitDelay().getNanos());
139144
}
140145
}
146+
147+
@Test
148+
public void testDefaultIsolationLevel() throws SQLException {
149+
for (IsolationLevel isolationLevel :
150+
Arrays.stream(IsolationLevel.values())
151+
.filter(level -> !level.equals(IsolationLevel.UNRECOGNIZED))
152+
.collect(Collectors.toList())) {
153+
try (java.sql.Connection connection =
154+
DriverManager.getConnection(
155+
"jdbc:" + getBaseUrl() + ";default_isolation_level=" + isolationLevel.name())) {
156+
connection.setAutoCommit(false);
157+
try (ResultSet resultSet =
158+
connection.createStatement().executeQuery(SELECT1_STATEMENT.getSql())) {
159+
while (resultSet.next()) {
160+
// ignore
161+
}
162+
}
163+
connection.commit();
164+
assertEquals(1, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class));
165+
ExecuteSqlRequest request = mockSpanner.getRequestsOfType(ExecuteSqlRequest.class).get(0);
166+
assertTrue(request.hasTransaction());
167+
assertTrue(request.getTransaction().hasBegin());
168+
assertTrue(request.getTransaction().getBegin().hasReadWrite());
169+
assertEquals(isolationLevel, request.getTransaction().getBegin().getIsolationLevel());
170+
assertEquals(1, mockSpanner.countRequestsOfType(CommitRequest.class));
171+
172+
mockSpanner.clearRequests();
173+
}
174+
}
175+
}
176+
177+
@Test
178+
public void testSetIsolationLevel() throws SQLException {
179+
try (java.sql.Connection connection = createJdbcConnection()) {
180+
connection.setAutoCommit(false);
181+
for (int isolationLevel :
182+
new int[] {Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE}) {
183+
connection.setTransactionIsolation(isolationLevel);
184+
try (ResultSet resultSet =
185+
connection.createStatement().executeQuery(SELECT1_STATEMENT.getSql())) {
186+
while (resultSet.next()) {
187+
// ignore
188+
}
189+
}
190+
connection.commit();
191+
assertEquals(1, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class));
192+
ExecuteSqlRequest request = mockSpanner.getRequestsOfType(ExecuteSqlRequest.class).get(0);
193+
assertTrue(request.hasTransaction());
194+
assertTrue(request.getTransaction().hasBegin());
195+
assertTrue(request.getTransaction().getBegin().hasReadWrite());
196+
assertEquals(
197+
IsolationLevelConverter.convertToSpanner(isolationLevel),
198+
request.getTransaction().getBegin().getIsolationLevel());
199+
assertEquals(1, mockSpanner.countRequestsOfType(CommitRequest.class));
200+
201+
mockSpanner.clearRequests();
202+
}
203+
}
204+
}
141205
}

0 commit comments

Comments
 (0)