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