Skip to content

Commit

Permalink
Test App: Add Java code for transaction retries
Browse files Browse the repository at this point in the history
Add example code for transaction retry logic. Compilation and
execution instructions are in a comment in the main code file.
Fixes cockroachdb#757.
  • Loading branch information
rjnn authored and Arjun Narayan committed Jan 11, 2017
1 parent 09bfdfd commit 3e91e90
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 12 deletions.
83 changes: 83 additions & 0 deletions _includes/app/TxnSample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import java.sql.*;

/*
You can compile and run this example with a command like:
javac TxnSample.java && java -cp .:~/path/to/postgresql-9.4.1208.jar TxnSample
You can download the postgres JDBC driver jar from https://jdbc.postgresql.org.
*/

class InsufficientBalanceException extends Exception {}

// A simple interface that provides a retryable lambda expression.
interface RetryableTransaction {
public void run(Connection conn) throws Exception;
}

public class TxnSample {
public static RetryableTransaction transferFunds(int from, int to, int amount) {
return new RetryableTransaction() {
public void run(Connection conn) throws Exception {
ResultSet res = conn.createStatement().executeQuery("SELECT balance FROM accounts WHERE id = " + from);
res.next();
int balance = res.getInt("balance");
if(balance < from) {
throw new InsufficientBalanceException();
}
conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance - " + amount + " where id = " + from);
conn.createStatement().executeUpdate("UPDATE accounts SET balance = balance + " + amount + " where id = " + to);
}
};
}

public static void retryTransaction(Connection conn, RetryableTransaction tx) throws Exception {
Savepoint sp = conn.setSavepoint("cockroach_restart");
while(true) {
try {
// Attempt the transaction.
tx.run(conn);

// If we reach this point, commit the transaction,
// which implicitly releases the savepoint.
conn.commit();
break;
} catch(SQLException e) {
// Check if the error code indicates a SERIALIZATION_FAILURE.
if(e.getErrorCode() == 40001) {
// Signal the database that we will attempt a retry.
conn.rollback(sp);
}
// This is a not a serialization failure, pass it up the chain.
throw e;
}
}
}

public static void main(String[] args) throws ClassNotFoundException, SQLException {
// Load the postgres JDBC driver.
Class.forName("org.postgresql.Driver");

// Connect to the "bank" database.
Connection db = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:26257/bank?sslmode=disable", "maxroach", "");
try {
// We need to turn off autocommit mode to allow for
// multi-statement transactions.
db.setAutoCommit(false);

RetryableTransaction transfer = transferFunds(1, 2, 100);
retryTransaction(db, transfer);
ResultSet res = db.createStatement().executeQuery("SELECT id, balance FROM accounts");
while (res.next()) {
System.out.printf("\taccount %s: %s\n", res.getInt("id"), res.getInt("balance"));
}
} catch(InsufficientBalanceException ibe) {
System.out.println("Insufficient balance");
} catch(SQLException sqle) {
System.out.println("SQLException encountered:" + sqle);
} catch(Exception e) {
System.out.println("Unknown exception encountered:" + e);
} finally {
// Close the database connection.
db.close();
}
}
}
Empty file removed _includes/app/txn-sample.java
Empty file.
24 changes: 12 additions & 12 deletions build-a-test-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ This page is CockroachDB's **Hello, World!** tutorial. It walks you through crea

Make sure you have already:

- [Installed CockroachDB](install-cockroachdb.html)
- [Installed CockroachDB](install-cockroachdb.html)
- [Started a local cluster](start-a-local-cluster.html) in insecure mode
- [Installed a client driver](install-client-drivers.html)

Feel free to watch this process in action before going through the steps yourself. Note that the demo video features Python code for executing basic statements (step 4), but the code for executing more complex transactions is not covered (step 5). Also note that you can copy commands directly from the video, and you can use **<** and **>** to go back and forward.

<asciinema-player class="asciinema-demo" src="asciicasts/build-a-test-app.json" cols="107" speed="2" theme="monokai" poster="npt:0:40" title="Build a Test App"></asciinema-player>

## Step 1. Create a user

As the `root` user, use the [`cockroach user`](create-and-manage-users.html) command to create a new user, `maxroach`.
Expand Down Expand Up @@ -59,7 +59,7 @@ As the `maxroach` user, use the [built-in SQL client](use-the-built-in-sql-clien

~~~ shell
$ cockroach sql --database=bank --user=maxroach -e \
'CREATE TABLE accounts (id INT PRIMARY KEY, balance INT)'
'CREATE TABLE accounts (id INT PRIMARY KEY, balance INT)'
~~~

~~~
Expand Down Expand Up @@ -164,9 +164,9 @@ Initial balances:

## Step 5. Execute transactions from a client

As the `maxroach` user, connect again from your preferred language, but this time execute a batch of statements as an atomic transaction, where all included statements are either commited or aborted.
As the `maxroach` user, connect again from your preferred language, but this time execute a batch of statements as an atomic transaction, where all included statements are either commited or aborted.

{{site.data.alerts.callout_info}}Because the CockroachDB transaction model requires the client to initiate retries in the case of contention, CockroachDB provides a generic <strong>retry function</strong> that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code. For more details, see <a href="https://www.cockroachlabs.com/docs/transactions.html#transaction-retries">Transaction Retries</a>.{{site.data.alerts.end}}
{{site.data.alerts.callout_info}}Because the CockroachDB transaction model requires the client to initiate retries in the case of contention, CockroachDB provides a generic <strong>retry function</strong> that runs inside a transaction and retries it as needed. You can copy and paste the retry function from here into your code. For more details, see <a href="https://www.cockroachlabs.com/docs/transactions.html#transaction-retries">Transaction Retries</a>.{{site.data.alerts.end}}

<div id="step-four-filters" class="filters clearfix">
<button class="filter-button current" data-language="python">Python</button>
Expand Down Expand Up @@ -200,8 +200,8 @@ Coming soon.
For Go, the CockroachDB retry function is in the `crdb` package of the CockroachDB Go client. You can clone the library into your `$GOPATH` as follows:

~~~ shell
$ mkdir -p $GOPATH/github.com/cockroachdb
$ cd $GOPATH/github.com/cockroachdb
$ mkdir -p $GOPATH/github.com/cockroachdb
$ cd $GOPATH/github.com/cockroachdb
$ git clone git@github.com:cockroachdb/cockroach-go.git
~~~

Expand All @@ -213,8 +213,9 @@ $ git clone git@github.com:cockroachdb/cockroach-go.git
<div class="filter-content" markdown="1" data-language="java">
**Java**

Coming soon.
</div>
~~~ java
{% include app/TxnSample.java %}
~~~

<div class="filter-content" markdown="1" data-language="nodejs">
**Node.js**
Expand Down Expand Up @@ -267,11 +268,11 @@ Use a local cluster to explore the following core CockroachDB features:

<script>
$(document).ready(function(){

var $filter_button = $('.filter-button');

$filter_button.on('click', function(){
var language = $(this).data('language'),
var language = $(this).data('language'),
$current_tab = $('.filter-button.current'), $current_content = $('.filter-content.current');

//remove current class from tab and content
Expand All @@ -284,4 +285,3 @@ $(document).ready(function(){
});
});
</script>

0 comments on commit 3e91e90

Please sign in to comment.