| 1 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?> |
| 2 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| 3 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
| 4 |
<head> |
| 5 |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> |
| 6 |
<title>Base API Transaction Example</title> |
| 7 |
<link rel="stylesheet" href="gettingStarted.css" type="text/css" /> |
| 8 |
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> |
| 9 |
<link rel="start" href="index.html" title="Getting Started with Berkeley DB Transaction Processing" /> |
| 10 |
<link rel="up" href="wrapup.html" title="Chapter 6. Summary and Examples" /> |
| 11 |
<link rel="prev" href="wrapup.html" title="Chapter 6. Summary and Examples" /> |
| 12 |
<link rel="next" href="txnexample_dpl.html" title="DPL Transaction Example" /> |
| 13 |
</head> |
| 14 |
<body> |
| 15 |
<div xmlns="" class="navheader"> |
| 16 |
<div class="libver"> |
| 17 |
<p>Library Version 11.2.5.3</p> |
| 18 |
</div> |
| 19 |
<table width="100%" summary="Navigation header"> |
| 20 |
<tr> |
| 21 |
<th colspan="3" align="center">Base API Transaction Example</th> |
| 22 |
</tr> |
| 23 |
<tr> |
| 24 |
<td width="20%" align="left"><a accesskey="p" href="wrapup.html">Prev</a> </td> |
| 25 |
<th width="60%" align="center">Chapter 6. Summary and Examples</th> |
| 26 |
<td width="20%" align="right"> <a accesskey="n" href="txnexample_dpl.html">Next</a></td> |
| 27 |
</tr> |
| 28 |
</table> |
| 29 |
<hr /> |
| 30 |
</div> |
| 31 |
<div class="sect1" lang="en" xml:lang="en"> |
| 32 |
<div class="titlepage"> |
| 33 |
<div> |
| 34 |
<div> |
| 35 |
<h2 class="title" style="clear: both"><a id="txnexample_java"></a>Base API Transaction Example</h2> |
| 36 |
</div> |
| 37 |
</div> |
| 38 |
</div> |
| 39 |
<div class="toc"> |
| 40 |
<dl> |
| 41 |
<dt> |
| 42 |
<span class="sect2"> |
| 43 |
<a href="txnexample_java.html#txnguideexample">TxnGuide.java</a> |
| 44 |
</span> |
| 45 |
</dt> |
| 46 |
<dt> |
| 47 |
<span class="sect2"> |
| 48 |
<a href="txnexample_java.html#payloaddata">PayloadData.java</a> |
| 49 |
</span> |
| 50 |
</dt> |
| 51 |
<dt> |
| 52 |
<span class="sect2"> |
| 53 |
<a href="txnexample_java.html#dbwriter">DBWriter.java</a> |
| 54 |
</span> |
| 55 |
</dt> |
| 56 |
</dl> |
| 57 |
</div> |
| 58 |
<p> |
| 59 |
The following Java code provides a fully functional example of a |
| 60 |
multi-threaded transactional DB application. |
| 61 |
The example opens an environment and database, and then creates 5 |
| 62 |
threads, each of which writes 500 records to the database. The keys |
| 63 |
used for these writes are pre-determined strings, while the data is |
| 64 |
a class that contains randomly generated data. This means that the actual |
| 65 |
data is arbitrary and therefore uninteresting; we picked it only |
| 66 |
because it requires minimum code to implement and therefore will |
| 67 |
stay out of the way of the main points of this example. |
| 68 |
</p> |
| 69 |
<p> |
| 70 |
Each thread writes 10 records under a single transaction |
| 71 |
before committing and writing another 10 (this is repeated 50 |
| 72 |
times). At the end of each transaction, but before committing, each |
| 73 |
thread calls a function that uses a cursor to read every record in |
| 74 |
the database. We do this in order to make some points about |
| 75 |
database reads in a transactional environment. |
| 76 |
</p> |
| 77 |
<p> |
| 78 |
Of course, each writer thread performs deadlock detection as |
| 79 |
described in this manual. In addition, normal recovery is performed |
| 80 |
when the environment is opened. |
| 81 |
</p> |
| 82 |
<p> |
| 83 |
To implement this example, we need three classes: |
| 84 |
</p> |
| 85 |
<div class="itemizedlist"> |
| 86 |
<ul type="disc"> |
| 87 |
<li> |
| 88 |
<p> |
| 89 |
<code class="literal">TxnGuide.java</code> |
| 90 |
</p> |
| 91 |
<p> |
| 92 |
This is the main class for the application. It performs |
| 93 |
environment and database management, spawns threads, and |
| 94 |
creates the data that is placed in the database. See <a class="xref" href="txnexample_java.html#txnguideexample" title="TxnGuide.java">TxnGuide.java</a> for implementation details. |
| 95 |
</p> |
| 96 |
</li> |
| 97 |
<li> |
| 98 |
<p> |
| 99 |
<code class="literal">DBWriter.java</code> |
| 100 |
</p> |
| 101 |
<p> |
| 102 |
This class extends <code class="literal">java.lang.Thread</code>, and |
| 103 |
as such it is our thread implementation. It is responsible |
| 104 |
for actually reading and writing to the database. It also |
| 105 |
performs all of our transaction management. See <a class="xref" href="txnexample_java.html#dbwriter" title="DBWriter.java">DBWriter.java</a> for |
| 106 |
implementation details. |
| 107 |
</p> |
| 108 |
</li> |
| 109 |
<li> |
| 110 |
<p> |
| 111 |
<code class="literal">PayloadData.java</code> |
| 112 |
</p> |
| 113 |
<p> |
| 114 |
This is a data class used to encapsulate several data |
| 115 |
fields. It is fairly uninteresting, except that the usage |
| 116 |
of a class means that we have to use the bind APIs to |
| 117 |
serialize it for storage in the database. See <a class="xref" href="txnexample_java.html#payloaddata" title="PayloadData.java">PayloadData.java</a> for |
| 118 |
implementation details. |
| 119 |
</p> |
| 120 |
</li> |
| 121 |
</ul> |
| 122 |
</div> |
| 123 |
<div class="sect2" lang="en" xml:lang="en"> |
| 124 |
<div class="titlepage"> |
| 125 |
<div> |
| 126 |
<div> |
| 127 |
<h3 class="title"><a id="txnguideexample"></a>TxnGuide.java</h3> |
| 128 |
</div> |
| 129 |
</div> |
| 130 |
</div> |
| 131 |
<p> |
| 132 |
The main class in our example application is used to open and |
| 133 |
close our environment and database. It also spawns all the |
| 134 |
threads that we need. We start with the normal series |
| 135 |
of Java package and import statements, followed by our class |
| 136 |
declaration: |
| 137 |
</p> |
| 138 |
<pre class="programlisting">// File TxnGuide.java |
| 139 |
|
| 140 |
package db.txn; |
| 141 |
|
| 142 |
import com.sleepycat.bind.serial.StoredClassCatalog; |
| 143 |
|
| 144 |
import com.sleepycat.db.Database; |
| 145 |
import com.sleepycat.db.DatabaseConfig; |
| 146 |
import com.sleepycat.db.DatabaseException; |
| 147 |
import com.sleepycat.db.DatabaseType; |
| 148 |
import com.sleepycat.db.LockDetectMode; |
| 149 |
|
| 150 |
import com.sleepycat.db.Environment; |
| 151 |
import com.sleepycat.db.EnvironmentConfig; |
| 152 |
|
| 153 |
import java.io.File; |
| 154 |
import java.io.FileNotFoundException; |
| 155 |
|
| 156 |
public class TxnGuide { </pre> |
| 157 |
<p> |
| 158 |
Next we declare our class' private data members. Mostly these are used |
| 159 |
for constants such as the name of the database that we are opening and |
| 160 |
the number of threads that we are spawning. However, we also declare |
| 161 |
our environment and database handles here. |
| 162 |
</p> |
| 163 |
<pre class="programlisting"> private static String myEnvPath = "./"; |
| 164 |
private static String dbName = "mydb.db"; |
| 165 |
private static String cdbName = "myclassdb.db"; |
| 166 |
|
| 167 |
// DB handles |
| 168 |
private static Database myDb = null; |
| 169 |
private static Database myClassDb = null; |
| 170 |
private static Environment myEnv = null; |
| 171 |
|
| 172 |
private static final int NUMTHREADS = 5; </pre> |
| 173 |
<p> |
| 174 |
Next, we implement our <code class="function">usage()</code> method. This |
| 175 |
application optionally accepts a single command line argument which is |
| 176 |
used to identify the environment home directory. |
| 177 |
</p> |
| 178 |
<pre class="programlisting"> private static void usage() { |
| 179 |
System.out.println("TxnGuide [-h <env directory>]"); |
| 180 |
System.exit(-1); |
| 181 |
} </pre> |
| 182 |
<p> |
| 183 |
Now we implement our <code class="function">main()</code> method. This method |
| 184 |
simply calls the methods to parse the command line arguments and open |
| 185 |
the environment and database. It also creates the stored class catalog |
| 186 |
that we use for serializing the data that we want to store in our |
| 187 |
database. Finally, it creates and then joins the database writer |
| 188 |
threads. |
| 189 |
</p> |
| 190 |
<pre class="programlisting"> public static void main(String args[]) { |
| 191 |
try { |
| 192 |
// Parse the arguments list |
| 193 |
parseArgs(args); |
| 194 |
// Open the environment and databases |
| 195 |
openEnv(); |
| 196 |
// Get our class catalog (used to serialize objects) |
| 197 |
StoredClassCatalog classCatalog = |
| 198 |
new StoredClassCatalog(myClassDb); |
| 199 |
|
| 200 |
// Start the threads |
| 201 |
DBWriter[] threadArray; |
| 202 |
threadArray = new DBWriter[NUMTHREADS]; |
| 203 |
for (int i = 0; i < NUMTHREADS; i++) { |
| 204 |
threadArray[i] = new DBWriter(myEnv, myDb, classCatalog); |
| 205 |
threadArray[i].start(); |
| 206 |
} |
| 207 |
|
| 208 |
// Join the threads. That is, wait for each thread to |
| 209 |
// complete before exiting the application. |
| 210 |
for (int i = 0; i < NUMTHREADS; i++) { |
| 211 |
threadArray[i].join(); |
| 212 |
} |
| 213 |
} catch (Exception e) { |
| 214 |
System.err.println("TxnGuide: " + e.toString()); |
| 215 |
e.printStackTrace(); |
| 216 |
} finally { |
| 217 |
closeEnv(); |
| 218 |
} |
| 219 |
System.out.println("All done."); |
| 220 |
} </pre> |
| 221 |
<p> |
| 222 |
Next we implement <code class="function">openEnv()</code>. This method is used |
| 223 |
to open the environment and then a database in that environment. Along |
| 224 |
the way, we make sure that every handle is free-threaded, and that the |
| 225 |
transactional subsystem is correctly initialized. Because this is a |
| 226 |
concurrent application, we also declare how we want deadlock detection |
| 227 |
to be performed. In this case, we use DB's internal block detector |
| 228 |
to determine whether a deadlock has occurred when a thread attempts to |
| 229 |
acquire a lock. We also indicate that we want the deadlocked thread |
| 230 |
with the <span class="emphasis"><em>youngest</em></span> lock to receive deadlock |
| 231 |
notification. |
| 232 |
</p> |
| 233 |
<p> |
| 234 |
Notice that we also cause normal recovery to be run when we open the |
| 235 |
environment. This is the standard and recommended thing to do whenever |
| 236 |
you start up a transactional application. |
| 237 |
</p> |
| 238 |
<p> |
| 239 |
For the database open, notice that we open the database such that it |
| 240 |
supports duplicate records. This is required purely by the data that |
| 241 |
we are writing to the database, and it is only necessary if you run the |
| 242 |
application more than once without first deleting the environment. |
| 243 |
</p> |
| 244 |
<p> |
| 245 |
Finally, notice that we open the database such that it supports |
| 246 |
uncommitted reads. We do this so that some cursor activity later in |
| 247 |
this example can read uncommitted data. If we did not do this, then |
| 248 |
our <code class="methodname">countRecords()</code> method described later in |
| 249 |
this example would cause our thread to self-deadlock. This is because |
| 250 |
the cursor could not be opened to support uncommitted reads (that flag |
| 251 |
on the cursor open would, in fact, be silently ignored). |
| 252 |
</p> |
| 253 |
<pre class="programlisting"> private static void openEnv() throws DatabaseException { |
| 254 |
System.out.println("opening env"); |
| 255 |
|
| 256 |
// Set up the environment. |
| 257 |
EnvironmentConfig myEnvConfig = new EnvironmentConfig(); |
| 258 |
myEnvConfig.setAllowCreate(true); |
| 259 |
myEnvConfig.setInitializeCache(true); |
| 260 |
myEnvConfig.setInitializeLocking(true); |
| 261 |
myEnvConfig.setInitializeLogging(true); |
| 262 |
myEnvConfig.setRunRecovery(true); |
| 263 |
myEnvConfig.setTransactional(true); |
| 264 |
// EnvironmentConfig.setThreaded(true) is the default behavior |
| 265 |
// in Java, so we do not have to do anything to cause the |
| 266 |
// environment handle to be free-threaded. |
| 267 |
|
| 268 |
// Indicate that we want db to internally perform deadlock |
| 269 |
// detection. Also indicate that the transaction that has |
| 270 |
// performed the least amount of write activity to |
| 271 |
// receive the deadlock notification, if any. |
| 272 |
myEnvConfig.setLockDetectMode(LockDetectMode.MINWRITE); |
| 273 |
|
| 274 |
// Set up the database |
| 275 |
DatabaseConfig myDbConfig = new DatabaseConfig(); |
| 276 |
myDbConfig.setType(DatabaseType.BTREE); |
| 277 |
myDbConfig.setAllowCreate(true); |
| 278 |
myDbConfig.setTransactional(true); |
| 279 |
myDbConfig.setSortedDuplicates(true); |
| 280 |
myDbConfig.setReadUncommitted(true); |
| 281 |
// no DatabaseConfig.setThreaded() method available. |
| 282 |
// db handles in java are free-threaded so long as the |
| 283 |
// env is also free-threaded. |
| 284 |
|
| 285 |
try { |
| 286 |
// Open the environment |
| 287 |
myEnv = new Environment(new File(myEnvPath), // Env home |
| 288 |
myEnvConfig); |
| 289 |
|
| 290 |
// Open the database. Do not provide a txn handle. This open |
| 291 |
// is auto committed because DatabaseConfig.setTransactional() |
| 292 |
// is true. |
| 293 |
myDb = myEnv.openDatabase(null, // txn handle |
| 294 |
dbName, // Database file name |
| 295 |
null, // Database name |
| 296 |
myDbConfig); |
| 297 |
|
| 298 |
// Used by the bind API for serializing objects |
| 299 |
// Class database must not support duplicates |
| 300 |
myDbConfig.setSortedDuplicates(false); |
| 301 |
myClassDb = myEnv.openDatabase(null, // txn handle |
| 302 |
cdbName, // Database file name |
| 303 |
null, // Database name, |
| 304 |
myDbConfig); |
| 305 |
} catch (FileNotFoundException fnfe) { |
| 306 |
System.err.println("openEnv: " + fnfe.toString()); |
| 307 |
System.exit(-1); |
| 308 |
} |
| 309 |
} </pre> |
| 310 |
<p> |
| 311 |
Finally, we implement the methods used to close our environment and |
| 312 |
databases, parse the command line arguments, and provide our class |
| 313 |
constructor. This is fairly standard code and it is mostly |
| 314 |
uninteresting from the perspective of this manual. We include it here |
| 315 |
purely for the purpose of completeness. |
| 316 |
</p> |
| 317 |
<pre class="programlisting"> private static void closeEnv() { |
| 318 |
System.out.println("Closing env and databases"); |
| 319 |
if (myDb != null ) { |
| 320 |
try { |
| 321 |
myDb.close(); |
| 322 |
} catch (DatabaseException e) { |
| 323 |
System.err.println("closeEnv: myDb: " + |
| 324 |
e.toString()); |
| 325 |
e.printStackTrace(); |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
if (myClassDb != null ) { |
| 330 |
try { |
| 331 |
myClassDb.close(); |
| 332 |
} catch (DatabaseException e) { |
| 333 |
System.err.println("closeEnv: myClassDb: " + |
| 334 |
e.toString()); |
| 335 |
e.printStackTrace(); |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
if (myEnv != null ) { |
| 340 |
try { |
| 341 |
myEnv.close(); |
| 342 |
} catch (DatabaseException e) { |
| 343 |
System.err.println("closeEnv: " + e.toString()); |
| 344 |
e.printStackTrace(); |
| 345 |
} |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
private TxnGuide() {} |
| 350 |
|
| 351 |
private static void parseArgs(String args[]) { |
| 352 |
for(int i = 0; i < args.length; ++i) { |
| 353 |
if (args[i].startsWith("-")) { |
| 354 |
switch(args[i].charAt(1)) { |
| 355 |
case 'h': |
| 356 |
myEnvPath = new String(args[++i]); |
| 357 |
break; |
| 358 |
default: |
| 359 |
usage(); |
| 360 |
} |
| 361 |
} |
| 362 |
} |
| 363 |
} |
| 364 |
} </pre> |
| 365 |
</div> |
| 366 |
<div class="sect2" lang="en" xml:lang="en"> |
| 367 |
<div class="titlepage"> |
| 368 |
<div> |
| 369 |
<div> |
| 370 |
<h3 class="title"><a id="payloaddata"></a>PayloadData.java</h3> |
| 371 |
</div> |
| 372 |
</div> |
| 373 |
</div> |
| 374 |
<p> |
| 375 |
Before we show the implementation of the database writer thread, we |
| 376 |
need to show the class that we will be placing into the database. This |
| 377 |
class is fairly minimal. It simply allows you to store and retrieve an |
| 378 |
<code class="literal">int</code>, a <code class="literal">String</code>, and a |
| 379 |
<code class="literal">double</code>. We will be using the DB bind API from |
| 380 |
within the writer thread to serialize instances of this class and place |
| 381 |
them into our database. |
| 382 |
</p> |
| 383 |
<pre class="programlisting">package db.txn; |
| 384 |
|
| 385 |
import java.io.Serializable; |
| 386 |
|
| 387 |
public class PayloadData implements Serializable { |
| 388 |
private int oID; |
| 389 |
private String threadName; |
| 390 |
private double doubleData; |
| 391 |
|
| 392 |
PayloadData(int id, String name, double data) { |
| 393 |
oID = id; |
| 394 |
threadName = name; |
| 395 |
doubleData = data; |
| 396 |
} |
| 397 |
|
| 398 |
public double getDoubleData() { return doubleData; } |
| 399 |
public int getID() { return oID; } |
| 400 |
public String getThreadName() { return threadName; } |
| 401 |
} </pre> |
| 402 |
</div> |
| 403 |
<div class="sect2" lang="en" xml:lang="en"> |
| 404 |
<div class="titlepage"> |
| 405 |
<div> |
| 406 |
<div> |
| 407 |
<h3 class="title"><a id="dbwriter"></a>DBWriter.java</h3> |
| 408 |
</div> |
| 409 |
</div> |
| 410 |
</div> |
| 411 |
<p> |
| 412 |
<code class="literal">DBWriter.java</code> provides the implementation |
| 413 |
for our database writer thread. It is responsible for: |
| 414 |
</p> |
| 415 |
<div class="itemizedlist"> |
| 416 |
<ul type="disc"> |
| 417 |
<li> |
| 418 |
<p> |
| 419 |
All transaction management. |
| 420 |
</p> |
| 421 |
</li> |
| 422 |
<li> |
| 423 |
<p> |
| 424 |
Responding to deadlock exceptions. |
| 425 |
</p> |
| 426 |
</li> |
| 427 |
<li> |
| 428 |
<p> |
| 429 |
Providing data to be stored into the database. |
| 430 |
</p> |
| 431 |
</li> |
| 432 |
<li> |
| 433 |
<p> |
| 434 |
Serializing and then writing the data to the database. |
| 435 |
</p> |
| 436 |
</li> |
| 437 |
</ul> |
| 438 |
</div> |
| 439 |
<p> |
| 440 |
In order to show off some of the ACID properties provided |
| 441 |
by DB's transactional support, |
| 442 |
<code class="literal">DBWriter.java</code> does some things in a less |
| 443 |
efficient way than you would probably decide to use in a |
| 444 |
true production application. First, it groups 10 database |
| 445 |
writes together in a single transaction when you could just |
| 446 |
as easily perform one write for each transaction. If you |
| 447 |
did this, you could use auto commit for the individual |
| 448 |
database writes, which means your code would be slightly |
| 449 |
simpler and you would run a <span class="emphasis"><em>much</em></span> |
| 450 |
smaller chance of encountering blocked and deadlocked |
| 451 |
operations. However, by doing things this way, we are able |
| 452 |
to show transactional atomicity, as well as deadlock |
| 453 |
handling. |
| 454 |
</p> |
| 455 |
<p> |
| 456 |
At the end of each transaction, |
| 457 |
<code class="literal">DBWriter.java</code> runs a cursor over the |
| 458 |
entire database by way of counting the number of records |
| 459 |
currently existing in the database. There are better ways |
| 460 |
to discover this information, but in this case we want to |
| 461 |
make some points regarding cursors, transactional |
| 462 |
applications, and deadlocking (we get into this in more |
| 463 |
detail later in this section). |
| 464 |
</p> |
| 465 |
<p> |
| 466 |
To begin, we provide the usual package and import statements, and we declare our class: |
| 467 |
</p> |
| 468 |
<pre class="programlisting">package db.txn; |
| 469 |
|
| 470 |
import com.sleepycat.bind.EntryBinding; |
| 471 |
import com.sleepycat.bind.serial.StoredClassCatalog; |
| 472 |
import com.sleepycat.bind.serial.SerialBinding; |
| 473 |
import com.sleepycat.bind.tuple.StringBinding; |
| 474 |
|
| 475 |
import com.sleepycat.db.Cursor; |
| 476 |
import com.sleepycat.db.CursorConfig; |
| 477 |
import com.sleepycat.db.Database; |
| 478 |
import com.sleepycat.db.DatabaseEntry; |
| 479 |
import com.sleepycat.db.DatabaseException; |
| 480 |
import com.sleepycat.db.DeadlockException; |
| 481 |
import com.sleepycat.db.Environment; |
| 482 |
import com.sleepycat.db.LockMode; |
| 483 |
import com.sleepycat.db.OperationStatus; |
| 484 |
import com.sleepycat.db.Transaction; |
| 485 |
|
| 486 |
import java.io.UnsupportedEncodingException; |
| 487 |
import java.util.Random; |
| 488 |
|
| 489 |
public class DBWriter extends Thread |
| 490 |
{ </pre> |
| 491 |
<p> |
| 492 |
Next we declare our private data members. Notice that we get handles |
| 493 |
for the environment and the database. We also obtain a handle for an |
| 494 |
<code class="classname">EntryBinding</code>. We will use this to serialize |
| 495 |
<code class="classname">PayloadData</code> class instances (see <a class="xref" href="txnexample_java.html#payloaddata" title="PayloadData.java">PayloadData.java</a>) for storage in |
| 496 |
the database. The random number generator that we instantiate is used |
| 497 |
to generate unique data for storage in the database. The |
| 498 |
<code class="literal">MAX_RETRY</code> variable is used to define how many times |
| 499 |
we will retry a transaction in the face of a deadlock. And, finally, |
| 500 |
<code class="literal">keys</code> is a <code class="classname">String</code> array that |
| 501 |
holds the keys used for our database entries. |
| 502 |
</p> |
| 503 |
<pre class="programlisting"> private Database myDb = null; |
| 504 |
private Environment myEnv = null; |
| 505 |
private EntryBinding dataBinding = null; |
| 506 |
private Random generator = new Random(); |
| 507 |
|
| 508 |
|
| 509 |
private static final int MAX_RETRY = 20; |
| 510 |
|
| 511 |
private static String[] keys = {"key 1", "key 2", "key 3", |
| 512 |
"key 4", "key 5", "key 6", |
| 513 |
"key 7", "key 8", "key 9", |
| 514 |
"key 10"}; </pre> |
| 515 |
<p> |
| 516 |
Next we implement our class constructor. The most interesting thing |
| 517 |
we do here is instantiate a serial binding for serializing |
| 518 |
<code class="classname">PayloadData</code> instances. |
| 519 |
</p> |
| 520 |
<pre class="programlisting"> // Constructor. Get our DB handles from here |
| 521 |
DBWriter(Environment env, Database db, StoredClassCatalog scc) |
| 522 |
throws DatabaseException { |
| 523 |
myDb = db; |
| 524 |
myEnv = env; |
| 525 |
dataBinding = new SerialBinding(scc, PayloadData.class); |
| 526 |
} </pre> |
| 527 |
<p> |
| 528 |
Now we implement our thread's <code class="methodname">run()</code> method. |
| 529 |
This is the method that is run when <code class="classname">DBWriter</code> |
| 530 |
threads are started in the main program (see <a class="xref" href="txnexample_java.html#txnguideexample" title="TxnGuide.java">TxnGuide.java</a>). |
| 531 |
</p> |
| 532 |
<pre class="programlisting"> // Thread method that writes a series of records |
| 533 |
// to the database using transaction protection. |
| 534 |
// Deadlock handling is demonstrated here. |
| 535 |
public void run () { </pre> |
| 536 |
<p> |
| 537 |
The first thing we do is get a <code class="literal">null</code> transaction |
| 538 |
handle before going into our main loop. We also begin the top transaction loop here that causes our application to |
| 539 |
perform 50 transactions. |
| 540 |
</p> |
| 541 |
<pre class="programlisting"> Transaction txn = null; |
| 542 |
|
| 543 |
// Perform 50 transactions |
| 544 |
for (int i=0; i<50; i++) { </pre> |
| 545 |
<p> |
| 546 |
Next we declare a <code class="literal">retry</code> variable. This is used to |
| 547 |
determine whether a deadlock should result in our retrying the |
| 548 |
operation. We also declare a <code class="literal">retry_count</code> variable |
| 549 |
that is used to make sure we do not retry a transaction forever in the |
| 550 |
unlikely event that the thread is unable to ever get a necessary lock. |
| 551 |
(The only thing that might cause this is if some other thread dies |
| 552 |
while holding an important lock. This is the only code that we have to |
| 553 |
guard against that because the simplicity of this application makes it |
| 554 |
highly unlikely that it will ever occur.) |
| 555 |
</p> |
| 556 |
<pre class="programlisting"> boolean retry = true; |
| 557 |
int retry_count = 0; |
| 558 |
// while loop is used for deadlock retries |
| 559 |
while (retry) { </pre> |
| 560 |
<p> |
| 561 |
Now we go into the <code class="literal">try</code> block that we use for |
| 562 |
deadlock detection. We also begin our transaction here. |
| 563 |
</p> |
| 564 |
<pre class="programlisting"> // try block used for deadlock detection and |
| 565 |
// general db exception handling |
| 566 |
try { |
| 567 |
|
| 568 |
// Get a transaction |
| 569 |
txn = myEnv.beginTransaction(null, null); </pre> |
| 570 |
<p> |
| 571 |
Now we write 10 records under the transaction that we have just begun. |
| 572 |
By combining multiple writes together under a single transaction, |
| 573 |
we increase the likelihood that a deadlock will occur. Normally, |
| 574 |
you want to reduce the potential for a deadlock and in this case |
| 575 |
the way to do that is to perform a single write per transaction. In |
| 576 |
other words, we <span class="emphasis"><em>should</em></span> be using auto commit to |
| 577 |
write to our database for this workload. |
| 578 |
</p> |
| 579 |
<p> |
| 580 |
However, we want to show deadlock handling and by performing |
| 581 |
multiple writes per transaction we can actually observe deadlocks |
| 582 |
occurring. We also want to underscore the idea that you can |
| 583 |
combing multiple database operations together in a single atomic |
| 584 |
unit of work. So for our example, we do the (slightly) wrong thing. |
| 585 |
</p> |
| 586 |
<p> |
| 587 |
Further, notice that we store our key into a |
| 588 |
<code class="classname">DatabaseEntry</code> using |
| 589 |
<code class="classname">com.sleepycat.bind.tuple.StringBinding</code> to |
| 590 |
perform the serialization. Also, when we instantiate the |
| 591 |
<code class="classname">PayloadData</code> object, we call |
| 592 |
<code class="methodname">getName()</code> which gives us the string |
| 593 |
representation of this thread's name, as well as |
| 594 |
<code class="methodname">Random.nextDouble()</code> which gives us a random |
| 595 |
double value. This latter value is used so as to avoid duplicate |
| 596 |
records in the database. |
| 597 |
</p> |
| 598 |
<pre class="programlisting"> |
| 599 |
// Write 10 records to the db |
| 600 |
// for each transaction |
| 601 |
for (int j = 0; j < 10; j++) { |
| 602 |
// Get the key |
| 603 |
DatabaseEntry key = new DatabaseEntry(); |
| 604 |
StringBinding.stringToEntry(keys[j], key); |
| 605 |
|
| 606 |
// Get the data |
| 607 |
PayloadData pd = new PayloadData(i+j, getName(), |
| 608 |
generator.nextDouble()); |
| 609 |
DatabaseEntry data = new DatabaseEntry(); |
| 610 |
dataBinding.objectToEntry(pd, data); |
| 611 |
|
| 612 |
// Do the put |
| 613 |
myDb.put(txn, key, data); |
| 614 |
} </pre> |
| 615 |
<p> |
| 616 |
Having completed the inner database write loop, we could simply |
| 617 |
commit the transaction and continue on to the next block of 10 |
| 618 |
writes. However, we want to first illustrate a few points about |
| 619 |
transactional processing so instead we call our |
| 620 |
<code class="function">countRecords()</code> method before calling the transaction |
| 621 |
commit. <code class="function">countRecords()</code> uses a cursor to read every |
| 622 |
record in the database and return a count of the number of records |
| 623 |
that it found. |
| 624 |
</p> |
| 625 |
<p> |
| 626 |
Because |
| 627 |
<code class="function">countRecords()</code> |
| 628 |
reads every record in the database, if used incorrectly the thread |
| 629 |
will self-deadlock. The writer thread has just written 500 records |
| 630 |
to the database, but because the transaction used for that write |
| 631 |
has not yet been committed, each of those 500 records are still |
| 632 |
locked by the thread's transaction. If we then simply run a |
| 633 |
non-transactional cursor over the database from within the same |
| 634 |
thread that has locked those 500 records, the cursor will |
| 635 |
block when it tries to read one of those transactional |
| 636 |
protected records. The thread immediately stops operation at that |
| 637 |
point while the cursor waits for the read lock it has |
| 638 |
requested. Because that read lock will never be released (the thread |
| 639 |
can never make any forward progress), this represents a |
| 640 |
self-deadlock for the thread. |
| 641 |
</p> |
| 642 |
<p> |
| 643 |
There are three ways to prevent this self-deadlock: |
| 644 |
</p> |
| 645 |
<div class="orderedlist"> |
| 646 |
<ol type="1"> |
| 647 |
<li> |
| 648 |
<p> |
| 649 |
We can move the call to |
| 650 |
<code class="function">countRecords()</code> to a point after the |
| 651 |
thread's transaction has committed. |
| 652 |
</p> |
| 653 |
</li> |
| 654 |
<li> |
| 655 |
<p> |
| 656 |
We can allow <code class="function">countRecords()</code> to |
| 657 |
operate under the same transaction as all of the writes |
| 658 |
were performed. |
| 659 |
</p> |
| 660 |
</li> |
| 661 |
<li> |
| 662 |
<p> |
| 663 |
We can reduce our isolation guarantee for the application |
| 664 |
by allowing uncommitted reads. |
| 665 |
</p> |
| 666 |
</li> |
| 667 |
</ol> |
| 668 |
</div> |
| 669 |
<p> |
| 670 |
For this example, we choose to use option 3 (uncommitted reads) to avoid |
| 671 |
the deadlock. This means that we have to open our database such |
| 672 |
that it supports uncommitted reads, and we have to open our cursor handle |
| 673 |
so that it knows to perform uncommitted reads. |
| 674 |
</p> |
| 675 |
<p> |
| 676 |
Note that in <a class="xref" href="inmem_txnexample_java.html" title="Base API In-Memory Transaction Example">Base API In-Memory Transaction Example</a>, |
| 677 |
we simply perform the cursor operation using the same transaction |
| 678 |
as is used for the thread's writes. |
| 679 |
</p> |
| 680 |
<pre class="programlisting"> // commit |
| 681 |
System.out.println(getName() + " : committing txn : " |
| 682 |
+ i); |
| 683 |
|
| 684 |
// Using uncommitted reads to avoid the deadlock, so |
| 685 |
// null is passed for the transaction here. |
| 686 |
System.out.println(getName() + " : Found " + |
| 687 |
countRecords(null) + " records in the database.");</pre> |
| 688 |
<p> |
| 689 |
Having performed this somewhat inelegant counting of the records in the |
| 690 |
database, we can now commit the transaction. |
| 691 |
</p> |
| 692 |
<pre class="programlisting"> try { |
| 693 |
txn.commit(); |
| 694 |
txn = null; |
| 695 |
} catch (DatabaseException e) { |
| 696 |
System.err.println("Error on txn commit: " + |
| 697 |
e.toString()); |
| 698 |
} |
| 699 |
retry = false; </pre> |
| 700 |
<p> |
| 701 |
If all goes well with the commit, we are done and we can move on to the |
| 702 |
next batch of 10 records to add to the database. However, in the event |
| 703 |
of an error, we must handle our exceptions correctly. The first of |
| 704 |
these is a deadlock exception. In the event of a deadlock, we want to |
| 705 |
abort and retry the transaction, provided that we have not already |
| 706 |
exceeded our retry limit for this transaction. |
| 707 |
</p> |
| 708 |
<pre class="programlisting"> } catch (DeadlockException de) { |
| 709 |
System.out.println("################# " + getName() + |
| 710 |
" : caught deadlock"); |
| 711 |
// retry if necessary |
| 712 |
if (retry_count < MAX_RETRY) { |
| 713 |
System.err.println(getName() + |
| 714 |
" : Retrying operation."); |
| 715 |
retry = true; |
| 716 |
retry_count++; |
| 717 |
} else { |
| 718 |
System.err.println(getName() + |
| 719 |
" : out of retries. Giving up."); |
| 720 |
retry = false; |
| 721 |
} </pre> |
| 722 |
<p> |
| 723 |
In the event of a standard, non-specific database exception, we simply |
| 724 |
log the exception and then give up (the transaction is not retried). |
| 725 |
</p> |
| 726 |
<pre class="programlisting"> } catch (DatabaseException e) { |
| 727 |
// abort and don't retry |
| 728 |
retry = false; |
| 729 |
System.err.println(getName() + |
| 730 |
" : caught exception: " + e.toString()); |
| 731 |
System.err.println(getName() + |
| 732 |
" : errno: " + e.getErrno()); |
| 733 |
e.printStackTrace(); </pre> |
| 734 |
<p> |
| 735 |
And, finally, we always abort the transaction if the transaction handle |
| 736 |
is not null. Note that immediately after committing our transaction, we |
| 737 |
set the transaction handle to null to guard against aborting a |
| 738 |
transaction that has already been committed. |
| 739 |
</p> |
| 740 |
<pre class="programlisting"> } finally { |
| 741 |
if (txn != null) { |
| 742 |
try { |
| 743 |
txn.abort(); |
| 744 |
} catch (Exception e) { |
| 745 |
System.err.println("Error aborting txn: " + |
| 746 |
e.toString()); |
| 747 |
e.printStackTrace(); |
| 748 |
} |
| 749 |
} |
| 750 |
} |
| 751 |
} |
| 752 |
} |
| 753 |
} </pre> |
| 754 |
<p> |
| 755 |
The final piece of our <code class="classname">DBWriter</code> class is the |
| 756 |
<code class="methodname">countRecords()</code> implementation. Notice how in |
| 757 |
this example we open the cursor such that it performs uncommitted |
| 758 |
reads: |
| 759 |
</p> |
| 760 |
<pre class="programlisting"> // A method that counts every record in the database. |
| 761 |
|
| 762 |
// Note that this method exists only for illustrative purposes. |
| 763 |
// A more straight-forward way to count the number of records in |
| 764 |
// a database is to use the Database.getStats() method. |
| 765 |
private int countRecords(Transaction txn) throws DatabaseException { |
| 766 |
DatabaseEntry key = new DatabaseEntry(); |
| 767 |
DatabaseEntry data = new DatabaseEntry(); |
| 768 |
int count = 0; |
| 769 |
Cursor cursor = null; |
| 770 |
|
| 771 |
try { |
| 772 |
// Get the cursor |
| 773 |
CursorConfig cc = new CursorConfig(); |
| 774 |
cc.setReadUncommitted(true); |
| 775 |
cursor = myDb.openCursor(txn, cc); |
| 776 |
while (cursor.getNext(key, data, LockMode.DEFAULT) == |
| 777 |
OperationStatus.SUCCESS) { |
| 778 |
|
| 779 |
count++; |
| 780 |
} |
| 781 |
} finally { |
| 782 |
if (cursor != null) { |
| 783 |
cursor.close(); |
| 784 |
} |
| 785 |
} |
| 786 |
|
| 787 |
return count; |
| 788 |
|
| 789 |
} |
| 790 |
} </pre> |
| 791 |
</div> |
| 792 |
<p> |
| 793 |
This completes our transactional example. If you would like to |
| 794 |
experiment with this code, you can find the example in the following |
| 795 |
location in your DB distribution: |
| 796 |
</p> |
| 797 |
<pre class="programlisting"><span class="emphasis"><em>DB_INSTALL</em></span>/examples_java/src/db/txn</pre> |
| 798 |
</div> |
| 799 |
<div class="navfooter"> |
| 800 |
<hr /> |
| 801 |
<table width="100%" summary="Navigation footer"> |
| 802 |
<tr> |
| 803 |
<td width="40%" align="left"><a accesskey="p" href="wrapup.html">Prev</a> </td> |
| 804 |
<td width="20%" align="center"> |
| 805 |
<a accesskey="u" href="wrapup.html">Up</a> |
| 806 |
</td> |
| 807 |
<td width="40%" align="right"> <a accesskey="n" href="txnexample_dpl.html">Next</a></td> |
| 808 |
</tr> |
| 809 |
<tr> |
| 810 |
<td width="40%" align="left" valign="top">Chapter 6. Summary and Examples </td> |
| 811 |
<td width="20%" align="center"> |
| 812 |
<a accesskey="h" href="index.html">Home</a> |
| 813 |
</td> |
| 814 |
<td width="40%" align="right" valign="top"> DPL Transaction Example</td> |
| 815 |
</tr> |
| 816 |
</table> |
| 817 |
</div> |
| 818 |
</body> |
| 819 |
</html> |