/usr/share/doc/libcommons-lang3-java/api/org/apache/commons/lang3/concurrent/package-summary.html is in libcommons-lang3-java-doc 3.5-2ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html>
<head>
<!-- Generated by javadoc -->
<title>org.apache.commons.lang3.concurrent (Apache Commons Lang 3.5 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../jquery/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.commons.lang3.concurrent (Apache Commons Lang 3.5 API)";
}
}
catch(err) {
}
//-->
var pathtoroot = "../../../../../";loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/commons/lang3/builder/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../org/apache/commons/lang3/event/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/commons/lang3/concurrent/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
<div class="header">
<h1 title="Package" class="title">Package org.apache.commons.lang3.concurrent</h1>
</div>
<div class="contentContainer"><a name="package.description">
<!-- -->
</a>
<div class="block"><p>Provides support classes for multi-threaded programming.
This package is intended to be an extension to <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html?is-external=true" class="externalLink"><code>java.util.concurrent</code></a>.
These classes are thread-safe.</p>
<h3></h3>
<p> A group of classes deals with the correct creation and initialization of objects that are accessed by multiple threads.
All these classes implement the <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentInitializer.html" title="interface in org.apache.commons.lang3.concurrent"><code>ConcurrentInitializer</code></a> interface which provides just a
single method:
</p>
<pre>
<code>
public interface ConcurrentInitializer<T> {
T get() throws ConcurrentException;
}
</code>
</pre>
<p>A <code>ConcurrentInitializer</code> produces an object.
By calling the <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentInitializer.html#get--"><code>get()</code></a> method the object managed by the initializer can be obtained.
There are different implementations of the interface available
addressing various use cases:
</p>
<p> <a href="../../../../../org/apache/commons/lang3/concurrent/ConstantInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>ConstantInitializer</code></a> is a very straightforward implementation of the <code>ConcurrentInitializer</code> interface:
An instance is passed an object when it is constructed.
In its <code>get()</code> method it simply returns this object.
This is useful, for instance in unit tests or in cases when you want to pass a specific object to a component which expects a <code>ConcurrentInitializer</code>.
</p>
<p>The <a href="../../../../../org/apache/commons/lang3/concurrent/LazyInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>LazyInitializer</code></a> class can be used to defer the creation of an object until it is actually used.
This makes sense, for instance, if the creation of the object is expensive and would slow down application startup or if the object is needed only for special executions.
<code>LazyInitializer</code> implements the <em>double-check idiom for an instance field</em> as discussed in Joshua Bloch's "Effective Java", 2nd edition, item 71.
It uses <strong>volatile</strong> fields to reduce the amount of synchronization.
Note that this idiom is appropriate for instance fields only.
For <strong>static</strong> fields there are superior alternatives.</p>
<p>We provide an example use case to demonstrate the usage of this class:
A server application uses multiple worker threads to process client requests.
If such a request causes a fatal error, an administrator is to be notified using a special messaging service.
We assume that the creation of the messaging service is an expensive operation.
So it should only be performed if an error actually occurs.
Here is where <code>LazyInitializer</code> comes into play.
We create a specialized subclass for creating and initializing an instance of our messaging service.
<code>LazyInitializer</code> declares an abstract <a href="../../../../../org/apache/commons/lang3/concurrent/LazyInitializer.html#initialize--"><code>initialize()</code></a> method which we have to implement to create the messaging service object:</p>
<pre>
<code>
public class MessagingServiceInitializer extends LazyInitializer<MessagingService> {
protected MessagingService initialize() throws ConcurrentException {
// Do all necessary steps to create and initialize the service object
MessagingService service = ...
return service;
}
}
</code>
</pre>
<p> Now each server thread is passed a reference to a shared instance of our new <code>MessagingServiceInitializer</code> class.
The threads run in a loop processing client requests. If an error is detected, the messaging service is obtained from the initializer, and the administrator is notified:</p>
<pre>
<code>
public class ServerThread implements Runnable {
// The initializer for obtaining the messaging service.
private final ConcurrentInitializer<MessagingService> initializer;
public ServerThread(ConcurrentInitializer<MessagingService> init) {
initializer = init;
}
public void run() {
while (true) {
try {
// wait for request
// process request
} catch (FatalServerException ex) {
// get messaging service
try {
MessagingService svc = initializer.get();
svc.notifyAdministrator(ex);
} catch (ConcurrentException cex) {
cex.printStackTrace();
}
}
}
}
}
</code>
</pre>
<p>The <a href="../../../../../org/apache/commons/lang3/concurrent/AtomicInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>AtomicInitializer</code></a> class is very similar to <code>LazyInitializer</code>.
It serves the same purpose: to defer the creation of an object until it is needed.
The internal structure is also very similar.
Again there is an abstract <a href="../../../../../org/apache/commons/lang3/concurrent/AtomicInitializer.html#initialize--"><code>initialize()</code></a> method which has to be implemented by concrete subclasses in order to create and initialize the managed object.
Actually, in our example above we can turn the <code>MessagingServiceInitializer</code> into an atomic initializer by simply changing the <strong>extends</strong> declaration to refer to <code>AtomicInitializer<MessagingService></code> as super class.</p>
<p>With <a href="../../../../../org/apache/commons/lang3/concurrent/AtomicSafeInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>AtomicSafeInitializer</code></a> there is yet another variant implementing the lazy initializing pattern.
Its implementation is close to <code>AtomicInitializer</code>; it also uses atomic variables internally and therefore does not need synchronization.
The name "Safe" is derived from the fact that it implements an additional check which guarantees that the <a href="../../../../../org/apache/commons/lang3/concurrent/AtomicSafeInitializer.html#initialize--"><code>initialize()</code></a> method is called only once.
So it behaves exactly in the same way as <code>LazyInitializer</code>.</p>
<p>Now, which one of the lazy initializer implementations should you use?
First of all we have to state that is is problematic to give general recommendations regarding the performance of these classes.
The initializers make use of low-level functionality whose efficiency depends on multiple factors including the target platform and the number of concurrent threads.
So developers should make their own benchmarks in scenarios close to their specific use cases.
The following statements are rules of thumb which have to be verified in practice.</p>
<p><code>AtomicInitializer</code> is probably the most efficient implementation due to its lack of synchronization and further checks.
Its main drawback is that the <code>initialize()</code> method can be called multiple times.
In cases where this is not an issue <code>AtomicInitializer</code> is a good choice.
<code>AtomicSafeInitializer</code> and <code>LazyInitializer</code> both guarantee that the initialization method is called only once.
Because <code>AtomicSafeInitializer</code> does not use synchronization it is probably slightly more efficient than <code>LazyInitializer</code>, but the concrete numbers might depend on the level of concurrency.</p>
<p>Another implementation of the <code>ConcurrentInitializer</code> interface is <a href="../../../../../org/apache/commons/lang3/concurrent/BackgroundInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>BackgroundInitializer</code></a>.
It is again an abstract base class with an <a href="../../../../../org/apache/commons/lang3/concurrent/BackgroundInitializer.html#initialize--"><code>initialize()</code></a> method that has to be defined by concrete subclasses.
The idea of <code>BackgroundInitializer</code> is that it calls the <code>initialize()</code> method in a separate worker thread.
An application creates a background initializer and starts it.
Then it can continue with its work while the initializer runs in parallel.
When the application needs the results of the initializer it calls its <code>get()</code> method.
<code>get()</code> blocks until the initialization is complete.
This is useful for instance at application startup.
Here initialization steps (e.g. reading configuration files, opening a database connection, etc.) can be run in background threads while the application shows a splash screen and constructs its UI.</p>
<p>As a concrete example consider an application that has to read the content of a URL - maybe a page with news - which is to be displayed to the user after login.
Because loading the data over the network can take some time a specialized implementation of <code>BackgroundInitializer</code> can be created for this purpose:</p>
<pre>
<code>
public class URLLoader extends BackgroundInitializer<String> {
// The URL to be loaded.
private final URL url;
public URLLoader(URL u) {
url = u;
}
protected String initialize() throws ConcurrentException {
try {
InputStream in = url.openStream();
// read content into string
...
return content;
} catch (IOException ioex) {
throw new ConcurrentException(ioex);
}
}
}
</code>
</pre>
<p>An application creates an instance of <code>URLLoader</code> and starts it.
Then it can do other things.
When it needs the content of the URL it calls the initializer's <code>get()</code> method:</p>
<pre>
<code>
URL url = new URL("http://www.application-home-page.com/");
URLLoader loader = new URLLoader(url);
loader.start(); // this starts the background initialization
// do other stuff
...
// now obtain the content of the URL
String content;
try {
content = loader.get(); // this may block
} catch (ConcurrentException cex) {
content = "Error when loading URL " + url;
}
// display content
</code>
</pre>
<p> Related to <code>BackgroundInitializer</code> is the <a href="../../../../../org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>MultiBackgroundInitializer</code></a> class.
As the name implies, this class can handle multiplie initializations in parallel.
The basic usage scenario is that a <code>MultiBackgroundInitializer</code> instance is created.
Then an arbitrary number of <code>BackgroundInitializer</code> objects is added using the <a href="../../../../../org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.html#addInitializer-java.lang.String-org.apache.commons.lang3.concurrent.BackgroundInitializer-"><code>MultiBackgroundInitializer.addInitializer(String, BackgroundInitializer)</code></a> method.
When adding an initializer a string has to be provided which is later used to obtain the result for this initializer.
When all initializers have been added the <a href="../../../../../org/apache/commons/lang3/concurrent/BackgroundInitializer.html#start--"><code>BackgroundInitializer.start()</code></a> method is called.
This starts processing of all initializers.
Later the <code>get()</code> method can be called.
It waits until all initializers have finished their initialization.
<code>get()</code> returns an object of type <a href="../../../../../org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.MultiBackgroundInitializerResults.html" title="class in org.apache.commons.lang3.concurrent"><code>MultiBackgroundInitializer.MultiBackgroundInitializerResults</code></a>.
This object provides information about all initializations that have been performed.
It can be checked whether a specific initializer was successful or threw an exception.
Of course, all initialization results can be queried.</p>
<p>With <code>MultiBackgroundInitializer</code> we can extend our example to perform multiple initialization steps.
Suppose that in addition to loading a web site we also want to create a JPA entity manager factory and read a configuration file.
We assume that corresponding <code>BackgroundInitializer</code> implementations exist.
The following example fragment shows the usage of <code>MultiBackgroundInitializer</code> for this purpose:</p>
<pre>
<code>
MultiBackgroundInitializer initializer = new MultiBackgroundInitializer();
initializer.addInitializer("url", new URLLoader(url));
initializer.addInitializer("jpa", new JPAEMFInitializer());
initializer.addInitializer("config", new ConfigurationInitializer());
initializer.start(); // start background processing
// do other interesting things in parallel
...
// evaluate the results of background initialization
MultiBackgroundInitializer.MultiBackgroundInitializerResults results =
initializer.get();
String urlContent = (String) results.getResultObject("url");
EntityManagerFactory emf =
(EntityManagerFactory) results.getResultObject("jpa");
...
</code>
</pre>
<p>The child initializers are added to the multi initializer and are assigned a unique name.
The object returned by the <code>get()</code> method is then queried for the single results using these unique names.</p>
<p> If background initializers - including <code>MultiBackgroundInitializer</code> - are created using the standard constructor, they create their own <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html?is-external=true" title="class or interface in java.util.concurrent" class="externalLink"><code>ExecutorService</code></a> which is used behind the scenes to execute the worker tasks.
It is also possible to pass in an <code>ExecutorService</code> when the initializer is constructed.
That way client code can configure the <code>ExecutorService</code> according to its specific needs; for instance, the number of threads available could be limited.</p>
<h3>Utility Classes</h3>
<p>Another group of classes in the new <code>concurrent</code> package offers some generic functionality related to concurrency.
There is the <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentUtils.html" title="class in org.apache.commons.lang3.concurrent"><code>ConcurrentUtils</code></a> class with a bunch of static utility methods.
One focus of this class is dealing with exceptions thrown by JDK classes.
Many JDK classes of the executor framework throw exceptions of type <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutionException.html?is-external=true" title="class or interface in java.util.concurrent" class="externalLink"><code>ExecutionException</code></a> if something goes wrong.
The root cause of these exceptions can also be a runtime exception or even an error.
In typical Java programming you often do not want to deal with runtime exceptions directly; rather you let them fall through the hierarchy of method invocations until they reach a central exception handler.
Checked exceptions in contrast are usually handled close to their occurrence.
With <code>ExecutionException</code> this principle is violated.
Because it is a checked exception, an application is forced to handle it even if the cause is a runtime exception.
So you typically have to inspect the cause of the <code>ExecutionException</code> and test whether it is a checked exception which has to be handled. If this is not the case, the causing exception can be rethrown.
</p>
<p>The <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentUtils.html#extractCause-java.util.concurrent.ExecutionException-"><code>ConcurrentUtils.extractCause(java.util.concurrent.ExecutionException)</code></a> method does this work for you.
It is passed an <code>ExecutionException</code> and tests its root cause.
If this is an error or a runtime exception, it is directly rethrown.
Otherwise, an instance of <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentException.html" title="class in org.apache.commons.lang3.concurrent"><code>ConcurrentException</code></a> is created and initialized with the root cause
(<code>ConcurrentException</code> is a new exception class in the <code>o.a.c.l.concurrent</code> package).
So if you get such a <code>ConcurrentException</code>, you can be sure that the original cause for the <code>ExecutionException</code> was a checked exception.
For users who prefer runtime exceptions in general there is also an <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentUtils.html#extractCauseUnchecked-java.util.concurrent.ExecutionException-"><code>ConcurrentUtils.extractCauseUnchecked(java.util.concurrent.ExecutionException)</code></a> method which behaves like <code>extractCause()</code>, but returns the unchecked exception <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentRuntimeException.html" title="class in org.apache.commons.lang3.concurrent"><code>ConcurrentRuntimeException</code></a> instead.</p>
<p>In addition to the <code>extractCause()</code> methods there are corresponding <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentUtils.html#handleCause-java.util.concurrent.ExecutionException-"><code>ConcurrentUtils.handleCause(java.util.concurrent.ExecutionException)</code></a> and <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentUtils.html#handleCauseUnchecked-java.util.concurrent.ExecutionException-"><code>ConcurrentUtils.handleCauseUnchecked(java.util.concurrent.ExecutionException)</code></a> methods.
These methods extract the cause of the passed in <code>ExecutionException</code> and throw the resulting <code>ConcurrentException</code> or <code>ConcurrentRuntimeException</code>.
This makes it easy to transform an <code>ExecutionException</code> into a <code>ConcurrentException</code> ignoring unchecked exceptions:</p>
<pre>
<code>
Future<Object> future = ...;
try {
Object result = future.get();
...
} catch (ExecutionException eex) {
ConcurrentUtils.handleCause(eex);
}
</code>
</pre>
<p>There is also some support for the concurrent initializers introduced in the last sub section.
The <code>initialize()</code> method is passed a <code>ConcurrentInitializer</code> object and returns the object created by this initializer.
It is null-safe.
The <code>initializeUnchecked()</code> method works analogously, but a <code>ConcurrentException</code> throws by the initializer is rethrown as a <code>ConcurrentRuntimeException</code>.
This is especially useful if the specific <code>ConcurrentInitializer</code> does not throw checked exceptions.
Using this method the code for requesting the object of an initializer becomes less verbose.
The direct invocation looks as follows:</p>
<pre>
<code>
ConcurrentInitializer<MyClass> initializer = ...;
try {
MyClass obj = initializer.get();
// do something with obj
} catch (ConcurrentException cex) {
// exception handling
}
</code>
</pre>
<p>Using the <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentUtils.html#initializeUnchecked-org.apache.commons.lang3.concurrent.ConcurrentInitializer-"><code>ConcurrentUtils.initializeUnchecked(ConcurrentInitializer)</code></a> method, this becomes:</p>
<pre>
<code>
ConcurrentInitializer<MyClass> initializer = ...;
MyClass obj = ConcurrentUtils.initializeUnchecked(initializer);
// do something with obj
</code>
</pre>
<p>Another utility class deals with the creation of threads.
When using the <em>Executor</em> framework new in JDK 1.5 the developer usually does not have to care about creating threads; the executors create the threads they need on demand.
However, sometimes it is desired to set some properties of the newly created worker threads.
This is possible through the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadFactory.html?is-external=true" title="class or interface in java.util.concurrent" class="externalLink"><code>ThreadFactory</code></a> interface; an implementation of this interface has to be created and passed to an executor on creation time.
Currently, the JDK does not provide an implementation of <code>ThreadFactory</code>, so one has to start from scratch. </p>
<p> With <a href="../../../../../org/apache/commons/lang3/concurrent/BasicThreadFactory.html" title="class in org.apache.commons.lang3.concurrent"><code>BasicThreadFactory</code></a> Commons Lang has an implementation of <code>ThreadFactory</code> that works out of the box for many common use cases.
For instance, it is possible to set a naming pattern for the new threads, set the daemon flag and a priority, or install a handler for uncaught exceptions.
Instances of <code>BasicThreadFactory</code> are created and configured using the nested <a href="../../../../../org/apache/commons/lang3/concurrent/BasicThreadFactory.Builder.html" title="class in org.apache.commons.lang3.concurrent"><code>BasicThreadFactory.Builder</code></a> class.
The following example shows a typical usage scenario:</p>
<pre>
<code>
BasicThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("worker-thread-%d")
.daemon(true)
.uncaughtExceptionHandler(myHandler)
.build();
ExecutorService exec = Executors.newSingleThreadExecutor(factory);
</code>
</pre>
<p>The nested <code>Builder</code> class defines some methods for configuring the new <code>BasicThreadFactory</code> instance.
Objects of this class are immutable, so these attributes cannot be changed later.
The naming pattern is a string which can be passed to <code>String.format()</code>.
The placeholder <em>%d</em> is replaced by an increasing counter value.
An instance can wrap another <code>ThreadFactory</code> implementation; this is achieved by calling the builder's <a href="../../../../../org/apache/commons/lang3/concurrent/BasicThreadFactory.Builder.html#wrappedFactory-java.util.concurrent.ThreadFactory-"><code>wrappedFactory(ThreadFactory)</code></a> method.
This factory is then used for creating new threads; after that the specific attributes are applied to the new thread.
If no wrapped factory is set, the default factory provided by the JDK is used.</p>
<h3>Synchronization objects</h3>
<p>The <code>concurrent</code> package also provides some support for specific synchronization problems with threads.</p>
<p> <a href="../../../../../org/apache/commons/lang3/concurrent/TimedSemaphore.html" title="class in org.apache.commons.lang3.concurrent"><code>TimedSemaphore</code></a> allows restricted access to a resource in a given time frame.
Similar to a semaphore, a number of permits can be acquired.
What is new is the fact that the permits available are related to a given time unit.
For instance, the timed semaphore can be configured to allow 10 permits in a second.
Now multiple threads access the semaphore and call its <a href="../../../../../org/apache/commons/lang3/concurrent/TimedSemaphore.html#acquire--"><code>TimedSemaphore.acquire()</code></a> method.
The semaphore keeps track about the number of granted permits in the current time frame.
Only 10 calls are allowed; if there are further callers, they are blocked until the time frame (one second in this example) is over.
Then all blocking threads are released, and the counter of available permits is reset to 0.
So the game can start anew.</p>
<p> What are use cases for <code>TimedSemaphore</code>?
One example is to artificially limit the load produced by multiple threads.
Consider a batch application accessing a database to extract statistical data.
The application runs multiple threads which issue database queries in parallel and perform some calculation on the results.
If the database to be processed is huge and is also used by a production system, multiple factors have to be balanced:
On one hand, the time required for the statistical evaluation should not take too long.
Therefore you will probably use a larger number of threads because most of its life time a thread will just wait for the database to return query results.
On the other hand, the load on the database generated by all these threads should be limited so that the responsiveness of the production system is not affected.
With a <code>TimedSemaphore</code> object this can be achieved.
The semaphore can be configured to allow e.g. 100 queries per second.
After these queries have been sent to the database the threads have to wait until the second is over - then they can query again.
By fine-tuning the limit enforced by the semaphore a good balance between performance and database load can be established.
It is even possible to chang? the number of available permits at runtime.
So this number can be reduced during the typical working hours and increased at night.</p>
<p>The following code examples demonstrate parts of the implementation of such a scenario.
First the batch application has to create an instance of <code>TimedSemaphore</code> and to initialize its properties with default values:</p>
<code>TimedSemaphore semaphore = new TimedSemaphore(1, TimeUnit.SECONDS, 100);</code>
<p>Here we specify that the semaphore should allow 100 permits in one second.
This is effectively the limit of database queries per second in our example use case.
Next the server threads issuing database queries and performing statistical operations can be initialized.
They are passed a reference to the semaphore at creation time. Before they execute a query they have to acquire a permit.</p>
<pre>
<code>
public class StatisticsTask implements Runnable {
// The semaphore for limiting database load.
private final TimedSemaphore semaphore;
public StatisticsTask(TimedSemaphore sem, Connection con) {
semaphore = sem;
...
}
//The main processing method. Executes queries and evaluates their results.
public void run() {
try {
while (!isDone()) {
semaphore.acquire(); // enforce the load limit
executeAndEvaluateQuery();
}
} catch (InterruptedException iex) {
// fall through
}
}
}
</code>
</pre>
<p>The important line here is the call to <code>semaphore.acquire()</code>.
If the number of permits in the current time frame has not yet been reached, the call returns immediately.
Otherwise, it blocks until the end of the time frame.
The last piece missing is a scheduler service which adapts the number of permits allowed by the semaphore according to the time of day.
We assume that this service is pretty simple and knows only two different time slots:
working shift and night shift.
The service is triggered periodically.
It then determines the current time slot and configures the timed semaphore accordingly.</p>
<pre>
<code>
public class SchedulerService {
// The semaphore for limiting database load.
private final TimedSemaphore semaphore;
...
// Configures the timed semaphore based on the current time of day. This method is called periodically.
public void configureTimedSemaphore() {
int limit;
if (isWorkshift()) {
limit = 50; // low database load
} else {
limit = 250; // high database load
}
semaphore.setLimit(limit);
}
}
</code>
</pre>
<p>With the <a href="../../../../../org/apache/commons/lang3/concurrent/TimedSemaphore.html#setLimit-int-"><code>TimedSemaphore.setLimit(int)</code></a> method the number of permits allowed for a time frame can be changed.
There are some other methods for querying the internal state of a timed semaphore.
Also some statistical data is available, e.g. the average number of <code>acquire()</code> calls per time frame.
When a timed semaphore is no more needed, its <code>shutdown()</code> method has to be called.</p></div>
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/CircuitBreaker.html" title="interface in org.apache.commons.lang3.concurrent">CircuitBreaker</a><T></th>
<td class="colLast">
<div class="block">
An interface describing a <a href="http://martinfowler.com/bliki/CircuitBreaker.html">Circuit Breaker</a> component.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentInitializer.html" title="interface in org.apache.commons.lang3.concurrent">ConcurrentInitializer</a><T></th>
<td class="colLast">
<div class="block">
Definition of an interface for the thread-safe initialization of objects.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.html" title="class in org.apache.commons.lang3.concurrent">AbstractCircuitBreaker</a><T></th>
<td class="colLast">
<div class="block">Base class for circuit breakers.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/AtomicInitializer.html" title="class in org.apache.commons.lang3.concurrent">AtomicInitializer</a><T></th>
<td class="colLast">
<div class="block">
A specialized implementation of the <code>ConcurrentInitializer</code> interface
based on an <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicReference.html?is-external=true" title="class or interface in java.util.concurrent.atomic" class="externalLink"><code>AtomicReference</code></a> variable.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/AtomicSafeInitializer.html" title="class in org.apache.commons.lang3.concurrent">AtomicSafeInitializer</a><T></th>
<td class="colLast">
<div class="block">
A specialized <code>ConcurrentInitializer</code> implementation which is similar
to <a href="../../../../../org/apache/commons/lang3/concurrent/AtomicInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>AtomicInitializer</code></a>, but ensures that the <a href="../../../../../org/apache/commons/lang3/concurrent/AtomicSafeInitializer.html#initialize--"><code>AtomicSafeInitializer.initialize()</code></a>
method is called only once.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/BackgroundInitializer.html" title="class in org.apache.commons.lang3.concurrent">BackgroundInitializer</a><T></th>
<td class="colLast">
<div class="block">
A class that allows complex initialization operations in a background task.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/BasicThreadFactory.html" title="class in org.apache.commons.lang3.concurrent">BasicThreadFactory</a></th>
<td class="colLast">
<div class="block">
An implementation of the <code>ThreadFactory</code> interface that provides some
configuration options for the threads it creates.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/BasicThreadFactory.Builder.html" title="class in org.apache.commons.lang3.concurrent">BasicThreadFactory.Builder</a></th>
<td class="colLast">
<div class="block">
A <em>builder</em> class for creating instances of <code>
BasicThreadFactory</code>.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/CallableBackgroundInitializer.html" title="class in org.apache.commons.lang3.concurrent">CallableBackgroundInitializer</a><T></th>
<td class="colLast">
<div class="block">
A specialized <a href="../../../../../org/apache/commons/lang3/concurrent/BackgroundInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>BackgroundInitializer</code></a> implementation that wraps a
<code>Callable</code> object.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentUtils.html" title="class in org.apache.commons.lang3.concurrent">ConcurrentUtils</a></th>
<td class="colLast">
<div class="block">
An utility class providing functionality related to the <code>
java.util.concurrent</code> package.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/ConstantInitializer.html" title="class in org.apache.commons.lang3.concurrent">ConstantInitializer</a><T></th>
<td class="colLast">
<div class="block">
A very simple implementation of the <a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentInitializer.html" title="interface in org.apache.commons.lang3.concurrent"><code>ConcurrentInitializer</code></a> interface
which always returns the same object.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/EventCountCircuitBreaker.html" title="class in org.apache.commons.lang3.concurrent">EventCountCircuitBreaker</a></th>
<td class="colLast">
<div class="block">
A simple implementation of the <a href="http://martinfowler.com/bliki/CircuitBreaker.html">Circuit Breaker</a> pattern
that counts specific events.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/LazyInitializer.html" title="class in org.apache.commons.lang3.concurrent">LazyInitializer</a><T></th>
<td class="colLast">
<div class="block">
This class provides a generic implementation of the lazy initialization
pattern.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.html" title="class in org.apache.commons.lang3.concurrent">MultiBackgroundInitializer</a></th>
<td class="colLast">
<div class="block">
A specialized <a href="../../../../../org/apache/commons/lang3/concurrent/BackgroundInitializer.html" title="class in org.apache.commons.lang3.concurrent"><code>BackgroundInitializer</code></a> implementation that can deal with
multiple background initialization tasks.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/MultiBackgroundInitializer.MultiBackgroundInitializerResults.html" title="class in org.apache.commons.lang3.concurrent">MultiBackgroundInitializer.MultiBackgroundInitializerResults</a></th>
<td class="colLast">
<div class="block">A data class for storing the results of the background initialization
performed by <code>MultiBackgroundInitializer</code>.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/ThresholdCircuitBreaker.html" title="class in org.apache.commons.lang3.concurrent">ThresholdCircuitBreaker</a></th>
<td class="colLast">
<div class="block">
A simple implementation of the <a href="http://martinfowler.com/bliki/CircuitBreaker.html">Circuit Breaker</a> pattern
that opens if the requested increment amount is greater than a given threshold.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/TimedSemaphore.html" title="class in org.apache.commons.lang3.concurrent">TimedSemaphore</a></th>
<td class="colLast">
<div class="block">
A specialized <em>semaphore</em> implementation that provides a number of
permits in a given time frame.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/AbstractCircuitBreaker.State.html" title="enum in org.apache.commons.lang3.concurrent">AbstractCircuitBreaker.State</a></th>
<td class="colLast">
<div class="block">An internal enumeration representing the different states of a circuit
breaker.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" summary="Exception Summary table, listing exceptions, and an explanation">
<caption><span>Exception Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Exception</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/CircuitBreakingException.html" title="class in org.apache.commons.lang3.concurrent">CircuitBreakingException</a></th>
<td class="colLast">
<div class="block">
An exception class used for reporting runtime error conditions related to
circuit breakers.</div>
</td>
</tr>
<tr class="rowColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentException.html" title="class in org.apache.commons.lang3.concurrent">ConcurrentException</a></th>
<td class="colLast">
<div class="block">
An exception class used for reporting error conditions related to accessing
data of background tasks.</div>
</td>
</tr>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="../../../../../org/apache/commons/lang3/concurrent/ConcurrentRuntimeException.html" title="class in org.apache.commons.lang3.concurrent">ConcurrentRuntimeException</a></th>
<td class="colLast">
<div class="block">
An exception class used for reporting runtime error conditions related to
accessing data of background tasks.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/commons/lang3/builder/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../org/apache/commons/lang3/event/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/commons/lang3/concurrent/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2001–2018. All rights reserved.</small></p>
</body>
</html>
|