-
Notifications
You must be signed in to change notification settings - Fork 8
/
service.transaction.control.html
8639 lines (8520 loc) · 947 KB
/
service.transaction.control.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>147 Transaction Control Service Specification - OSGi Compendium 8</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
<link rel="home" href="index.html" title="OSGi Compendium" />
<link rel="up" href="index.html" title="OSGi Compendium" />
<link rel="prev" href="service.serial.html" title="146 Serial Device Service Specification" />
<link rel="next" href="service.clusterinfo.html" title="148 Cluster Information Specification" />
<meta name="Section-title" content="147 Transaction Control Service Specification" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" href="images/favicon.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="css/custom.css" />
<link rel="stylesheet" type="text/css" href="css/github.css" />
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin" /><script type="text/javascript" src="js/highlight.pack.js"></script><script type="text/javascript" src="js/main.js"></script></head>
<body>
<div id="fullbody">
<div id="header">
<div class="menu-top-container"></div>
<div id="shadow-block"><a class="logo" href="index.html"><img src="images/OSGi.svg" alt="OSGi Working Group Documentation" /><h1>OSGi Compendium Release 8</h1></a></div>
</div>
<div id="mobile-menu-icon">⋮</div>
<div id="column-two">
<div id="content">
<div id="scrollable">
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<td width="20%" align="left"><a accesskey="p" href="service.serial.html">Prev</a>
</td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="service.clusterinfo.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="chapter">
<div xmlns="" class="titlepage">
<div>
<div>
<h1 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="service.transaction.control"></a><span xmlns="" class="number">147</span> Transaction Control Service Specification
</h1>
</div>
<div>
<p xmlns="http://www.w3.org/1999/xhtml" class="releaseinfo"><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control" title="147.9 org.osgi.service.transaction.control">Version 1.0</a></p>
</div>
</div>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h2 xmlns="http://www.w3.org/1999/xhtml" class="title" style="clear: both"><a xmlns="" class="anchor" id="d0e108814"></a><span xmlns="" class="number">147.1</span> Introduction
</h2>
</div>
</div>
</div>
<p>Software Transactions are an important aspect of most modern
applications. The job of a Transaction is to ensure logical consistency
for units of work within the application. Any time that the application
accesses a persistent external resource then a Transaction ensures that
the set of changes made to the resource(s) are Atomic, Consistent,
Isolated, and Durable (ACID).
</p>
<p>There are a variety of techniques for managing the lifecycle of
software Transactions used in an application. The most primitive
mechanisms are for the application code to directly interact with the
Transaction Manager, but higher level abstractions can automatically
manage the lifecycle of Transactions through the use of Aspect Oriented
Programming. Whatever techniques are used to manage the Transaction
lifecycle it is also necessary for any resource access that occurs within
the Transaction to be registered with the Transaction manager. As with
managing the Transaction lifecycle, this work may be performed by the
client, or by a an intermediate framework without direct action from the
client.
</p>
<p>OSGi applications consist of a set of independent modules which
interact via the OSGi service registry; as such there is no single
container which can be relied upon to manage the range of tasks needed to
successfully use a Transaction. This leaves OSGi clients with little
choice but to depend on specific environments, sacrificing portability, or
to directly use Transactions via the <a xmlns="" class="xref" href="service.jta.html" title="123 JTA Transaction Services Specification"><em xmlns="http://www.w3.org/1999/xhtml">JTA Transaction Services Specification</em></a>. The
purpose of the Transaction Control Service is twofold:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<p>To enable a portable, modular abstraction for Transaction
lifecycle management
</p>
</li>
<li class="listitem">
<p>To allow different resource types to be easily used within a
Transaction
</p>
</li>
</ul>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e108832"></a><span xmlns="" class="number">147.1.1</span> Essentials
</h3>
</div>
</div>
</div>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<p><span class="emphasis"><em>Scoped Work</em></span> - A function or code block
with an associated execution context, known as a Scope. The Scope
may be <span class="emphasis"><em>Transactional</em></span>, that is, associated with
a Transaction, or a <span class="emphasis"><em>No Transaction Scope</em></span>, that
is, with no associated Transaction.
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Client</em></span> - Application code that wishes to
invoke one or more pieces of Scoped Work.
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Transaction Control Service</em></span> - The OSGi
service representing the Transaction Control Service implementation.
Used by the Client to execute pieces of Scoped Work.
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Resource</em></span> - A local or remote software
component which is stateful and can participate in a
transaction.
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Resource Provider</em></span> - A service or object
which provides managed access to a Scoped Resource, that is, a
managed connection to the Resource which integrates with ongoing
Transactions as necessary.
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Transaction Context</em></span> - A Java object
representing the state of a Scope
</p>
</li>
</ul>
</div>
<div class="figure"><a xmlns="" class="anchor" id="d0e108872"></a><p class="title"><strong>Figure <span xmlns="" class="number">147</span>.1 Class and Service overview</strong></p>
<div class="figure-contents">
<div class="mediaobject" align="center"><img src="images/147-transaction-control-classes.png" align="middle" width="630" height="189" alt="Class and Service overview" /></div>
</div>
</div><br class="figure-break" /></div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e108878"></a><span xmlns="" class="number">147.1.2</span> Entities
</h3>
</div>
</div>
</div>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<p><span class="emphasis"><em>Transaction Control Service</em></span> - A service
that can execute pieces of work within a Scope, and be queried to
establish the current Scope.
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Client</em></span> - The code that requests for Work
to be run in a particular Scope.
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Work</em></span> - A collection of instructions that
interact with zero or more Resources within a Scope
</p>
</li>
<li class="listitem">
<p><span class="emphasis"><em>Scoped Resource</em></span> - A resource connection
with a managed lifecycle. The connection will automatically
participate in Transactions associated with Transactional Scopes,
and its lifecycle is tied to the Scope within which it is
used.
</p>
</li>
</ul>
</div>
</div>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h2 xmlns="http://www.w3.org/1999/xhtml" class="title" style="clear: both"><a xmlns="" class="anchor" id="d0e108902"></a><span xmlns="" class="number">147.2</span> Usage
</h2>
</div>
</div>
</div>
<p>This section is an introduction in the usage of the Transaction
Control Service. It is not the formal specification, the normative part
starts at <a xmlns="" class="xref" href="service.transaction.control.html#service.transaction.control-main.body" title="147.3 Transaction Control Service">Transaction Control Service</a>. This
section leaves out some of the details for clarity.
</p>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e108909"></a><span xmlns="" class="number">147.2.1</span> Synopsis
</h3>
</div>
</div>
</div>
<p>The Transaction Control Service provides a mechanism for a client
to run work within a defined Scope. Typically a Scope is also associated
with a Transaction. The purpose of a Scope is to simplify the lifecycle
of resources, and to allow those resources to participate in any ongoing
Transaction. Any Scoped Resources accessed during a Scope will remain
available throughout the scope, and be automatically cleaned up when the
Scope completes.
</p>
<p>Each Scope is started by the Client by passing piece of work to
the Transaction Control Service. The transaction control service will
then begin a scope if needed, execute the work, and then complete the
scope if needed. The different methods on the Transaction Control
Service provide different lifecycle semantics for the Scope. Some
methods establish a Transactional Scope, others may suspend an active
Transactional Scope replacing it with a No Transaction Scope.
</p>
<p>When a piece of Scoped Work is executing it may access one or more
Scoped Resources. When a Scoped Resource is first accessed within a
Scope it is bound to that Scope so that future accesses use the same
physical resource. At the end of the Scope the resource is detached from
the scope and the physical resource is released. If the Scope is
Transactional then the Scoped Resource will also participate in the
transaction.
</p>
<p>At the end of a piece of Scoped Work the Scope is finished. For a
No Transaction Scope this simply involves calling any registered
callbacks. For a Transactional Scope, however, the Transaction must be
completed or rolled back. If the Scoped Work exits normally, and no call
has been made to force the Transaction to roll back, then the
Transaction will commit. If, however, the Work exits with an Exception
or the Transaction has been marked for roll back, then the Transaction
will roll back. The result of the Work then flows back to the caller in
an appropriate way.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="service.transaction.control-simple-usage"></a><span xmlns="" class="number">147.2.2</span> Running Scoped Work
</h3>
</div>
</div>
</div>
<p>The general pattern for a client is to obtain the Transaction
Control Service and one or more Resource Provider instances. The
Resource Provider(s) may come from the Service Registry, or from a
Factory, and are used to create Scoped Resource instances. These
instances can then be used in the scoped work. This is demonstrated in
the following example:
</p><pre xmlns="" class="programlisting"><code>@Reference
TransactionControl control;
Connection connection;
@Reference
void setResourceProvider(JDBCConnectionProvider provider) {
connection = provider.getResrouce(control)
}
public void addMessage(String message) {
control.required(() -> {
PreparedStatement ps = connection.prepareStatement(
"Insert into TEST_TABLE values ( ? )");
ps.setString(1, message);
return ps.executeUpdate();
});
}
public List<String> listMessages(String message) {
control.notSupported(() -> {
List<String> results = new ArrayList<String>();
ResultSet rs = connection.createStatement()
.executeQuery("Select * from TEST_TABLE");
while(rs.next()) {
results.add(rs.getString(1));
}
return results;
});
}</code></pre><p>This example demonstrates how simply clients can execute scoped
work using the Transaction Control Service. In this case write
operations always occur in a Transactional Scope, but read operations
may occur in a Transactional Scope <span class="emphasis"><em>or</em></span> a No
Transaction Scope. In all cases the lifecycle of the underlying
connection is automatically managed, and there is no need to close or
commit the connection.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e108932"></a><span xmlns="" class="number">147.2.3</span> Accessing Scoped Resources
</h3>
</div>
</div>
</div>
<p>The Transaction Control Service can be used to manage the Scope of
any piece of Work, but Scopes are primarily used to simplify resource
lifecycle management when using Scoped Resources. A Scoped Resource is
created using a Resource Provider, and the returned object can then be
used in any scope to access the associated Resource.
</p>
<p>The example in <a xmlns="" class="xref" href="service.transaction.control.html#service.transaction.control-simple-usage" title="147.2.2 Running Scoped Work">Running Scoped Work</a> uses a
<code class="code">JDBCConnectionProvider</code>, which is a specialization of the
generic <code class="code">ResourceProvider</code> interface that returns JDBC
<code class="code">Connection</code> objects. Other specializations of the Resource
Provider exist in this specification, and third party providers may
provide their own specializations for proprietary resource types.
</p>
<p>Once a Resource Provider has been obtained, a Scoped Resource is
created from it by passing the Transaction Control Service to the
<code class="code">getResource</code> method. This returns the Scoped Resource object
that can then be used in Scoped Work.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e108955"></a><span xmlns="" class="number">147.2.4</span> Exception Management
</h3>
</div>
</div>
</div>
<p>One of the most significant sources of error in applications that
use transactions is caused by incorrect Exception Handling. These errors
are the primary reason for using a framework or container to manage
transactions, rather than trying to manage them in the application
code.
</p>
<p>Exceptions tend to be more common in code that makes use of
transactions because the code is usually performing actions that may
fail, for example making updates to a database. Also, many of these
exceptions (such as <code class="code">java.sql.SQLException</code>) are checked
exceptions. As Scoped Work will typically raise both checked and
unchecked exceptions it is defined as a <code class="code">Callable</code>. As the
callable interface <code class="code">throws Exception</code> it is not necessary to
catch or wrap any exception generated within Scoped Work.
</p><pre xmlns="" class="programlisting"><code>// An SQLException may be raised by the query,
// but we don't need to catch it
control.required(() -> connection.createStatement()
.executeQuery("Insert into TEST_TABLE values ( 'Hello World!' )"));</code></pre><p>An exception indicates that a problem has occurred in a piece of
code therefore, by default, any exception thrown from inside a
Transactional Scope will cause the Transaction to roll back. This means
that the Scoped Work can safely ignore any updates that were made in the
event of an exception.
</p>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e108975"></a><span xmlns="" class="number">147.2.4.1</span> Handling Exceptions
</h4>
</div>
</div>
</div>
<p>Scoped Work is free to throw checked or unchecked exceptions,
however these exceptions cannot be directly thrown on by the
Transaction Control Service. The primary reason for this is that
directly rethrowing the exception would force users of the Transaction
Control Service to either:
</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<p>Declare <code class="code">throws Exception</code> on the calling
method
</p>
</li>
<li class="listitem">
<p>Add <code class="code">try/catch Exception</code> blocks around the calls
to the Transaction Control Service.
</p>
</li>
</ul>
</div>
<p>Both of these solutions are undesirable, as they force
unnecessary boilerplate code, and potentially shadow real checked
exceptions in the API. Exceptions generated as part of Scoped Work are
therefore wrapped by the Transaction Control Service in a
<code class="code">ScopedWorkException</code>. <code class="code">ScopedWorkException</code> is
an unchecked exception and so can be ignored if no special handling is
required.
</p>
<p>In the case where the callers API requires the unwrapped
exception type to be thrown a <code class="code">ScopedWorkException</code> can be
easily unwrapped using the <code class="code">as</code> method.
</p><pre xmlns="" class="programlisting"><code>try {
control.required(() -> connection.createStatement()
.executeQuery("Insert into TEST_TABLE values ( 'Hello World!' )"));
} catch (ScopedWorkException swe) {
// This line throws the cause of the ScopedWorkException as
// an SQLException or as a RuntimeException if appropriate
throw swe.as(SQLException.class);
}</code></pre><p>If there is more than one potential checked Exception type that
should be rethrown then the <code class="code">asOneOf</code> method can be
used.
</p><pre xmlns="" class="programlisting"><code>try {
control.required(() -> connection.createStatement()
.executeQuery("Insert into TEST_TABLE values ( 'Hello World!' )"));
} catch (ScopedWorkException swe) {
// This line throws the cause of the ScopedWorkException as
// an SQLException or as a RuntimeException if appropriate
throw swe.asOneOf(SQLRecoverableException.class, SQLTransientException.class);
}</code></pre></div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109018"></a><span xmlns="" class="number">147.2.4.2</span> Avoiding Transaction Rollback
</h4>
</div>
</div>
</div>
<p>In general if a piece of Work running in a Transactional Scope
exits with an exception the associated Transaction will roll back.
Sometimes, however, certain exception types should not cause the
Transaction to roll back. This can be indicated to the Transaction
Control Service when the Scope is being declared.
</p><pre xmlns="" class="programlisting"><code>control.build()
.noRollbackFor(URISyntaxException.class)
.required(() -> {
...
});</code></pre><p>In this example the Transaction does not roll back for any
<code class="code">URISyntaxException</code>. Sometimes this is too coarse grained,
and the Transaction should only avoid rolling back for one specific
exception instance. In this case the instance can be passed to the
Transaction Control Service <code class="code">ignoreException</code>
method.
</p><pre xmlns="" class="programlisting"><code>control.required(() -> {
try {
// A URISynaxException from here is safe
...
} catch (URISyntaxException e) {
control.ignoreException(e);
throw e;
}
// A URISynaxException from here is *not* safe
...
});</code></pre></div>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109035"></a><span xmlns="" class="number">147.2.5</span> Multi Threading
</h3>
</div>
</div>
</div>
<p>By its very definition a Scope is associated with a single piece
of Work, and therefore a single thread. If a piece of Scoped Work starts
new threads, or submits tasks to other threads, then any code executed
on those threads will not occur within the Scope.
</p>
<p>Scoped Resources are always thread-safe, and can be used
concurrently in different Scopes. This is true even if the underlying
physical resources are not thread safe. It is the responsibility of the
Scoped Resource implementation to ensure that the underlying physical
resources are protected correctly.
</p>
</div>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h2 xmlns="http://www.w3.org/1999/xhtml" class="title" style="clear: both"><a xmlns="" class="anchor" id="service.transaction.control-main.body"></a><span xmlns="" class="number">147.3</span> Transaction Control Service
</h2>
</div>
</div>
</div>
<p>The Transaction Control Service is the primary interaction point
between a client and the Transaction Control Service implementation. A
Transaction Control Service implementation must expose a service
implementing the <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionControl" title="147.9.7 public interface TransactionControl extends TransactionStarter">TransactionControl</a> interface.
</p>
<p>Clients obtain an instance of the Transaction Control Service using
the normal OSGi service registry mechanisms, either directly using the
OSGi framework API, or using dependency injection.
</p>
<p>The Transaction Control Service is used to:</p>
<div class="itemizedlist">
<ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
<p>Execute work within a defined scope</p>
</li>
<li class="listitem">
<p>Query the current execution scope</p>
</li>
<li class="listitem">
<p>Associate objects with the current execution scope</p>
</li>
<li class="listitem">
<p>Register for callbacks when the scope ends</p>
</li>
<li class="listitem">
<p>Enlist resource with the current transaction (if there is a
Transaction Scope active)
</p>
</li>
<li class="listitem">
<p>Mark the current scope for rollback (if there is a Transaction
scope)
</p>
</li>
</ul>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109072"></a><span xmlns="" class="number">147.3.1</span> Scope Life Cycle
</h3>
</div>
</div>
</div>
<p>The life cycle of a scope is tied to the execution of a piece of
scoped work. Unless a scope is being inherited then a scope starts
immediately before the scoped work executes and ends immediately after
the scoped work completes, even if the scoped work throws an
exception.
</p>
<p>The first action that a client wishing to execute scoped work must
take is to identify the type of scope that they wish to use. The work
should then be passed to the relevant method on the TransactionControl
service:
</p>
<div class="table"><a xmlns="" class="anchor" id="d0e109079"></a><p class="title"><strong>Table <span xmlns="" class="number">147</span>.1 Methods for executing scoped work</strong></p>
<div class="table-contents">
<table summary="Methods for executing scoped work" width="100%" style="border-collapse: collapse;border-top: 0.5pt solid ; border-bottom: 0.5pt solid ; border-left: 0.5pt solid ; border-right: 0.5pt solid ; ">
<colgroup>
<col />
<col />
<col />
</colgroup>
<thead>
<tr>
<th style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Method Name</th>
<th style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Existing Scope</th>
<th style="border-bottom: 0.5pt solid ; ">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.required-Callable-" title="147.9.10.2 public T required(Callable<T> work) throws TransactionException, TransactionRolledBackException, ScopedWorkException">required(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Unscoped</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Begins a new Transaction scope and executes the
work inside it
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.required-Callable-" title="147.9.10.2 public T required(Callable<T> work) throws TransactionException, TransactionRolledBackException, ScopedWorkException">required(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">No Transaction scope</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Suspends the No Transaction Scope and begins a new
Transaction scope, executing the work inside it. After the work
completes the original scope is restored.
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.required-Callable-" title="147.9.10.2 public T required(Callable<T> work) throws TransactionException, TransactionRolledBackException, ScopedWorkException">required(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Transaction scope</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Runs the work within the existing
scope
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.requiresNew-Callable-" title="147.9.10.3 public T requiresNew(Callable<T> work) throws TransactionException, TransactionRolledBackException, ScopedWorkException">requiresNew(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Unscoped</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Begins a new Transaction scope and executes the
work inside it
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.requiresNew-Callable-" title="147.9.10.3 public T requiresNew(Callable<T> work) throws TransactionException, TransactionRolledBackException, ScopedWorkException">requiresNew(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">No Transaction scope</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Suspends the No Transaction Scope and begins a new
Transaction scope, executing the work inside it. After the work
completes the original scope is restored.
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.requiresNew-Callable-" title="147.9.10.3 public T requiresNew(Callable<T> work) throws TransactionException, TransactionRolledBackException, ScopedWorkException">requiresNew(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Transaction scope</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Suspends the Transaction Scope and begins a new
Transaction scope, executing the work inside it. After the work
completes the original scope is restored.
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.supports-Callable-" title="147.9.10.4 public T supports(Callable<T> work) throws TransactionException, ScopedWorkException">supports(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Unscoped</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Begins a new No Transaction scope and executes the
work inside it
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.supports-Callable-" title="147.9.10.4 public T supports(Callable<T> work) throws TransactionException, ScopedWorkException">supports(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">No Transaction scope</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Runs the work within the existing
scope
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.supports-Callable-" title="147.9.10.4 public T supports(Callable<T> work) throws TransactionException, ScopedWorkException">supports(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Transaction scope</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Runs the work within the existing
scope
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.notSupported-Callable-" title="147.9.10.1 public T notSupported(Callable<T> work) throws TransactionException, ScopedWorkException">notSupported(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">Unscoped</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Begins a new No Transaction scope and executes the
work inside it
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.notSupported-Callable-" title="147.9.10.1 public T notSupported(Callable<T> work) throws TransactionException, ScopedWorkException">notSupported(Callable)</a></td>
<td style="border-right: 0.5pt solid ; border-bottom: 0.5pt solid ; ">No Transaction scope</td>
<td style="border-bottom: 0.5pt solid ; ">
<p>Runs the work within the existing
scope
</p>
</td>
</tr>
<tr>
<td style="border-right: 0.5pt solid ; "><a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionStarter.notSupported-Callable-" title="147.9.10.1 public T notSupported(Callable<T> work) throws TransactionException, ScopedWorkException">notSupported(Callable)</a></td>
<td style="border-right: 0.5pt solid ; ">Transaction scope</td>
<td style="">
<p>Suspends the Transaction Scope and begins a new No
Transaction scope, executing the work inside it. After the work
completes the original transaction scope is
restored.
</p>
</td>
</tr>
</tbody>
</table>
</div>
</div><br class="table-break" /><p>Once the relevant method has been identified the client passes the
scoped work to the Transaction Control Service. In the typical case the
Transaction Control Service must then:
</p>
<div class="orderedlist">
<ol class="orderedlist" type="1">
<li class="listitem">
<p>Establish a new scope</p>
</li>
<li class="listitem">
<p>Execute the scoped work</p>
</li>
<li class="listitem">
<p>Finish the scope, calling any registered callbacks and
committing the Transaction if the scope is a Transaction
Scope
</p>
</li>
<li class="listitem">
<p>Return the result of the scoped work to the client</p>
</li>
</ol>
</div>
<p>The Transaction Control Service must only finish a scope once,
after the execution of the Scoped Work which originally started the
scope. This means that callbacks registered by a piece of Scoped Work
may not run immediately after the work finishes, but will be delayed
until the parent task has finished if the scope was inherited.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109208"></a><span xmlns="" class="number">147.3.2</span> Scopes and Exception Management
</h3>
</div>
</div>
</div>
<p>Resource access is intrinsically error-prone, and therefore there
are many potential failure scenarios. Exceptions therefore form an
important part of the scope lifecycle.
</p>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109213"></a><span xmlns="" class="number">147.3.2.1</span> Client Exceptions
</h4>
</div>
</div>
</div>
<p>The work provided by the client to the Transaction Control
Service is passed as a <code class="code">Callable</code>, meaning that the work
may throw an Exception. An Exception thrown by the work is known as a
<span class="emphasis"><em>Client Exception</em></span>.
</p>
<p>If a client exception is thrown then it must be caught by the
Transaction Control Service and handled appropriately by finishing the
scope as required. Once the scope has completed the client exception
must be wrapped in a <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.ScopedWorkException" title="147.9.4 public class ScopedWorkException extends RuntimeException">ScopedWorkException</a> and rethrown by the Transaction Control
service.
</p>
<p>If a number of scopes are nested then a ScopedWorkException may
be received as a client Exception. A ScopedWorkException must not be
re-wrapped by the Transaction Control Service using the normal
Exception chaining mechanism, but instead a new ScopedWorkException
must be created initialized with the original cause. The caught
ScopedWorkException must then be added to the new ScopedWorkException
as a suppressed Exception. This prevents clients from having to deeply
introspect the exception cause chain to locate the original
error.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109230"></a><span xmlns="" class="number">147.3.2.2</span> Rethrowing Client Exceptions
</h4>
</div>
</div>
</div>
<p>In the general case clients will not need to catch a
ScopedWorkException, and it can be left to report/handle at a higher
level. Sometimes, however, the Exceptions thrown by a piece of work
represent an important part of the API, and they need to be thrown on
without being wrapped in a ScopedWorkException. The
ScopedWorkException provides a simple mechanism to do this. The client
simply calls one of the <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.ScopedWorkException.asOneOf-Class-Class-" title="147.9.4.3 public RuntimeException asOneOf(Class<A> a, Class<B> b) throws A, B">asOneOf(Class,Class)</a> methods which will throw the cause of the
Exception as one of the supplied checked Exception types, or directly
as an unchecked Exception if the cause is unchecked.
</p>
<p>The <code class="code">asOneOf()</code> methods always throw an Exception,
but the method return value is declared as a RuntimeException. This
can be used to simplify the act of rethrowing the cause when using
this method.
</p><pre xmlns="" class="programlisting"><code>try {
txControl.required(() -> {
// Do some work in here that may throw IOException
// or ClassNotFoundException
return result;
});
} catch (ScopedWorkException swe) {
throw swe.asOneOf(IOException.class, ClassNotFoundException.class);
}</code></pre><p>If the cause of a ScopedWorkException is a checked exception,
but that exception is not assignable to any of the types passed to the
<code class="code">asOneOf()</code> method then the cause of the
ScopedWorkException will still be thrown, however there will be no
compiler assistance for the user when writing their
<code class="code">throws</code> clause.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109252"></a><span xmlns="" class="number">147.3.2.3</span> Exceptions Generated by the Transaction Control Service
</h4>
</div>
</div>
</div>
<p>Many operations performed by the Transaction Control Service,
particularly when finishing a scope, may result in an Exception.
Internal failures, for example a failure when attempting to commit a
resource, must be wrapped in a <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionException" title="147.9.8 public class TransactionException extends RuntimeException">TransactionException</a> and thrown to the client.
</p>
<p>A TransactionException must never override a
ScopedWorkException. In the case where a ScopedWorkException should be
thrown and a Transaction Control Service failure occurs then the
TransactionException must be set as a suppressed exception in the
ScopedWorkException.
</p>
</div>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h3 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109261"></a><span xmlns="" class="number">147.3.3</span> Transaction Scope lifecycle
</h3>
</div>
</div>
</div>
<p>In addition to callbacks and scoped variables Transaction scopes
also provide an ongoing software transaction which shares the lifecycle
of the scope. There are therefore additional lifecycle rules for
Transaction Scopes
</p>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109266"></a><span xmlns="" class="number">147.3.3.1</span> Triggering Rollback in Transaction Scopes
</h4>
</div>
</div>
</div>
<p>By default a transaction will commit automatically when the
piece of work completes normally. If this is not desired (for example
if the work's business logic determines that the transaction should
not complete) then the work may trigger a rollback in one of two
ways.
</p>
<p>Calling <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionControl.setRollbackOnly--" title="147.9.7.7 public void setRollbackOnly() throws IllegalStateException">setRollbackOnly()</a> on the Transaction Control object will mark
the transaction for rollback so that it will never commit, even if the
method completes normally. This is a one-way operation, and the
rollback state can be queried using <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionControl.getRollbackOnly--" title="147.9.7.5 public boolean getRollbackOnly() throws IllegalStateException">getRollbackOnly()</a></p><pre xmlns="" class="programlisting"><code>txControl.required(() -> {
// Do some work in here
...
// This work will not be committed!
txControl.setRollbackOnly();
return result;
});</code></pre><p>Throwing an exception from the piece of work will, by default,
cause the transaction to be rolled back. Note that this is different
from Java EE behavior, where a checked exceptions <span class="emphasis"><em>does
not</em></span> trigger rollback. This is a deliberate difference as
many applications get the wrong behavior based on this default. For
example SQLException is a commonly thrown Exception in JDBC, but is
rarely, if ever, a “safe return”. Forgetting to override this behavior
means that production code will fail to enforce the correct
transaction boundaries.
</p><pre xmlns="" class="programlisting"><code>txControl.required(() -> {
// Do some work in here
...
// Uh oh – something went wrong!
throw new IllegalStateException(“Kaboom!”);
});</code></pre></div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109285"></a><span xmlns="" class="number">147.3.3.2</span> Avoiding Rollback
</h4>
</div>
</div>
</div>
<p>Sometimes it is preferable for a piece of work to throw an
exception, but for that exception not to trigger a rollback of the
transaction. For example some business exceptions may be considered
“normal”, or it may be the case that the work performed so far must be
persisted for audit reasons.
</p>
<p>There are two ways to prevent a transaction from rolling back
when a particular exception occurs
</p>
<p>The Transaction Control service provides a <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionBuilder" title="147.9.5 public abstract class TransactionBuilder implements TransactionStarter">TransactionBuilder</a>. The builder can be used to define sets of
Exception types that should, or should not, trigger rollback. The most
specific match will be used to determine whether the transaction
should roll back or not.
</p>
<p>The Transaction Control service provides an <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionControl.ignoreException-Throwable-" title="147.9.7.6 public void ignoreException(Throwable t) throws IllegalStateException">ignoreException(Throwable)</a> method. This can be used from within an Active
Transaction to declare a specific Exception object that should not
trigger rollback.
</p>
<p>If a transaction is marked for rollback using
<code class="code">setRollbackOnly()</code> then it must roll back, even if the
work throws an exception which would not normally trigger a
rollback.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109305"></a><span xmlns="" class="number">147.3.3.3</span> Rollback in inherited transactions
</h4>
</div>
</div>
</div>
<p>If a piece of scoped work inherits a transaction scope then the
transaction is not committed until the inherited scope completes.
Therefore if the nested scoped work throws an exception then this must
mark the transaction for rollback, unless the exception has been
explicitly ignored or configured not to cause rollback.
</p>
<p>Any exception thrown by the nested scoped work must result in a
<code class="code">ScopedWorkException</code> in exactly the same way as it would
when not nested.
</p><pre xmlns="" class="programlisting"><code>txControl.required(() -> {
// Do some work in here
...
try {
txControl.required(() -> {
// The outer transaction is inherited
throw new RuntimeException();
});
} catch (ScopedWorkException swe) {
// The transaction is still active, but now marked for rollback
}
});</code></pre></div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h4 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109317"></a><span xmlns="" class="number">147.3.3.4</span> Read Only transactions
</h4>
</div>
</div>
</div>
<p>Resources accessed within a transaction are frequently used to
update persistent data, however in some cases it is known in advance
that no changes will be made to the data. In the case where no changes
are going to be made then different, more optimal, algorithms can be
used by the resource to improve performance. It is therefore useful
for applications to be able to indicate when resources are going to be
used in a read-only way.
</p>
<p>To indicate that a transaction is read-only the
TransactionBuilder must be used.
</p><pre xmlns="" class="programlisting"><code>txControl.build()
.readOnly()
.required(() -> {
// Do some work in here
...
return result;
});</code></pre><p>The readOnly method provides a hint to the TransactionControl
service that the scoped work only uses read access to resources. The
TransactionControl service is free to ignore this hint if it does not
offer read-only optimizations. Also, read-only only applies to
Transaction Scopes. No Transaction Scopes always ignore the call to
readOnly.
</p>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h5 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109328"></a><span xmlns="" class="number">147.3.3.4.1</span> Determining whether a Transaction is read only
</h5>
</div>
</div>
</div>
<p>The TransactionContext provides access to whether the
transaction is read only using the <a xmlns="" class="xref" href="service.transaction.control.html#org.osgi.service.transaction.control.TransactionContext.isReadOnly--" title="147.9.6.5 public boolean isReadOnly()">isReadOnly()</a> method. This method will return true if the
transaction was started using the read only flag, and the
TransactionControl service supports read-only optimization.
</p>
<p>This method is primarily available so that resource providers
can set their read-only status correctly when they first enlist with
the transaction. Resource providers are free to ignore the read only
status as it is provided for optimization only.
</p>
</div>
<div class="section">
<div xmlns="" class="titlepage">
<div>
<div>
<h5 xmlns="http://www.w3.org/1999/xhtml" class="title"><a xmlns="" class="anchor" id="d0e109337"></a><span xmlns="" class="number">147.3.3.4.2</span> Writing to resources using in a read only transaction
</h5>
</div>
</div>
</div>
<p>When a client begins a transaction in read-only mode there is
no API restriction that prevents them from writing to one or more
resources. If the scoped work does write to the resource then the
result is undefined. The write may succeed, or it may result in an
exception, triggering a rollback.
</p>
<p>Clients should avoid declaring a transaction as read only
unless they are certain that no resources are updated within the