| 1 | /* |
| 2 | * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | * contributor license agreements. See the NOTICE file distributed with |
| 4 | * this work for additional information regarding copyright ownership. |
| 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | * (the "License"); you may not use this file except in compliance with |
| 7 | * the License. You may obtain a copy of the License at |
| 8 | * |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
| 17 | |
| 18 | /** |
| 19 | * Provides support classes for multi-threaded programming. This package is intended to be an extension to |
| 20 | * {@link java.util.concurrent}. These classes are thread-safe. |
| 21 | * |
| 22 | * <p> |
| 23 | * A group of classes deals with the correct creation and initialization of objects that are accessed by multiple |
| 24 | * threads. All these classes implement the {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer} interface |
| 25 | * which provides just a single method: |
| 26 | * </p> |
| 27 | * |
| 28 | * <pre>{@code |
| 29 | * public interface ConcurrentInitializer<T> { |
| 30 | * T get() throws ConcurrentException; |
| 31 | * } |
| 32 | * } |
| 33 | * </pre> |
| 34 | * |
| 35 | * <p> |
| 36 | * A {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer} produces an object. By calling the |
| 37 | * {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer#get() get()} method the object managed by the |
| 38 | * initializer can be obtained. There are different implementations of the interface available addressing various use |
| 39 | * cases: |
| 40 | * </p> |
| 41 | * |
| 42 | * <p> |
| 43 | * {@link org.apache.commons.lang3.concurrent.ConstantInitializer} is a very straightforward implementation of the |
| 44 | * {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer} interface: An instance is passed an object when it |
| 45 | * is constructed. In its {@code get()} method it simply returns this object. This is useful, for instance in unit tests |
| 46 | * or in cases when you want to pass a specific object to a component which expects a |
| 47 | * {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer}. |
| 48 | * </p> |
| 49 | * |
| 50 | * <p> |
| 51 | * The {@link org.apache.commons.lang3.concurrent.LazyInitializer} class can be used to defer the creation of an object |
| 52 | * until it is actually used. This makes sense, for instance, if the creation of the object is expensive and would slow |
| 53 | * down application startup or if the object is needed only for special executions. |
| 54 | * {@link org.apache.commons.lang3.concurrent.LazyInitializer} implements the <em>double-check idiom for an instance |
| 55 | * field</em> as discussed in Joshua Bloch's "Effective Java", 2nd edition, item 71. It uses <strong>volatile</strong> |
| 56 | * fields to reduce the amount of synchronization. Note that this idiom is appropriate for instance fields only. For |
| 57 | * <strong>static</strong> fields there are superior alternatives. |
| 58 | * </p> |
| 59 | * |
| 60 | * <p> |
| 61 | * We provide an example use case to demonstrate the usage of this class: A server application uses multiple worker |
| 62 | * threads to process client requests. If such a request causes a fatal error, an administrator is to be notified using |
| 63 | * a special messaging service. We assume that the creation of the messaging service is an expensive operation. So it |
| 64 | * should only be performed if an error actually occurs. Here is where |
| 65 | * {@link org.apache.commons.lang3.concurrent.LazyInitializer} comes into play. We create a specialized subclass for |
| 66 | * creating and initializing an instance of our messaging service. |
| 67 | * {@link org.apache.commons.lang3.concurrent.LazyInitializer} declares an abstract |
| 68 | * {@link org.apache.commons.lang3.concurrent.LazyInitializer#initialize() initialize()} method which we have to |
| 69 | * implement to create the messaging service object: |
| 70 | * </p> |
| 71 | * |
| 72 | * <pre>{@code |
| 73 | * public class MessagingServiceInitializer extends LazyInitializer<MessagingService> { |
| 74 | * protected MessagingService initialize() throws ConcurrentException { |
| 75 | * // Do all necessary steps to create and initialize the service object |
| 76 | * MessagingService service = ... |
| 77 | * return service; |
| 78 | * } |
| 79 | * } |
| 80 | * } |
| 81 | * </pre> |
| 82 | * |
| 83 | * <p> |
| 84 | * Now each server thread is passed a reference to a shared instance of our new {@code MessagingServiceInitializer} |
| 85 | * class. The threads run in a loop processing client requests. If an error is detected, the messaging service is |
| 86 | * obtained from the initializer, and the administrator is notified: |
| 87 | * </p> |
| 88 | * |
| 89 | * <pre>{@code |
| 90 | * public class ServerThread implements Runnable { |
| 91 | * // The initializer for obtaining the messaging service. |
| 92 | * private final ConcurrentInitializer<MessagingService> initializer; |
| 93 | * |
| 94 | * public ServerThread(ConcurrentInitializer<MessagingService> init) { |
| 95 | * initializer = init; |
| 96 | * } |
| 97 | * |
| 98 | * public void run() { |
| 99 | * while (true) { |
| 100 | * try { |
| 101 | * // wait for request |
| 102 | * // process request |
| 103 | * } catch (FatalServerException ex) { |
| 104 | * // get messaging service |
| 105 | * try { |
| 106 | * MessagingService svc = initializer.get(); |
| 107 | * svc.notifyAdministrator(ex); |
| 108 | * } catch (ConcurrentException cex) { |
| 109 | * cex.printStackTrace(); |
| 110 | * } |
| 111 | * } |
| 112 | * } |
| 113 | * } |
| 114 | * } |
| 115 | * } |
| 116 | * </pre> |
| 117 | * |
| 118 | * <p> |
| 119 | * The {@link org.apache.commons.lang3.concurrent.AtomicInitializer} class is very similar to |
| 120 | * {@link org.apache.commons.lang3.concurrent.LazyInitializer}. It serves the same purpose: to defer the creation of an |
| 121 | * object until it is needed. The internal structure is also very similar. Again there is an abstract |
| 122 | * {@link org.apache.commons.lang3.concurrent.AtomicInitializer#initialize() initialize()} method which has to be |
| 123 | * implemented by concrete subclasses in order to create and initialize the managed object. Actually, in our example |
| 124 | * above we can turn the {@code MessagingServiceInitializer} into an atomic initializer by simply changing the |
| 125 | * <strong>extends</strong> declaration to refer to {@code AtomicInitializer<MessagingService>} as super class. |
| 126 | * </p> |
| 127 | * |
| 128 | * <p> |
| 129 | * With {@link org.apache.commons.lang3.concurrent.AtomicSafeInitializer} there is yet another variant implementing the |
| 130 | * lazy initializing pattern. Its implementation is close to |
| 131 | * {@link org.apache.commons.lang3.concurrent.AtomicInitializer}; it also uses atomic variables internally and therefore |
| 132 | * does not need synchronization. The name "Safe" is derived from the fact that it implements an additional |
| 133 | * check which guarantees that the {@link org.apache.commons.lang3.concurrent.AtomicSafeInitializer#initialize() |
| 134 | * initialize()} method is called only once. So it behaves exactly in the same way as |
| 135 | * {@link org.apache.commons.lang3.concurrent.LazyInitializer}. |
| 136 | * </p> |
| 137 | * |
| 138 | * <p> |
| 139 | * Now, which one of the lazy initializer implementations should you use? First of all we have to state that is |
| 140 | * problematic to give general recommendations regarding the performance of these classes. The initializers make use of |
| 141 | * low-level functionality whose efficiency depends on multiple factors including the target platform and the number of |
| 142 | * concurrent threads. So developers should make their own benchmarks in scenarios close to their specific use cases. |
| 143 | * The following statements are rules of thumb which have to be verified in practice. |
| 144 | * </p> |
| 145 | * |
| 146 | * <p> |
| 147 | * {@link org.apache.commons.lang3.concurrent.AtomicInitializer} is probably the most efficient implementation due to |
| 148 | * its lack of synchronization and further checks. Its main drawback is that the {@code initialize()} method can be |
| 149 | * called multiple times. In cases where this is not an issue |
| 150 | * {@link org.apache.commons.lang3.concurrent.AtomicInitializer} is a good choice. |
| 151 | * {@link org.apache.commons.lang3.concurrent.AtomicSafeInitializer} and |
| 152 | * {@link org.apache.commons.lang3.concurrent.LazyInitializer} both guarantee that the initialization method is called |
| 153 | * only once. Because {@link org.apache.commons.lang3.concurrent.AtomicSafeInitializer} does not use synchronization it |
| 154 | * is probably slightly more efficient than {@link org.apache.commons.lang3.concurrent.LazyInitializer}, but the |
| 155 | * concrete numbers might depend on the level of concurrency. |
| 156 | * </p> |
| 157 | * |
| 158 | * <p> |
| 159 | * Another implementation of the {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer} interface is |
| 160 | * {@link org.apache.commons.lang3.concurrent.BackgroundInitializer}. It is again an abstract base class with an |
| 161 | * {@link org.apache.commons.lang3.concurrent.BackgroundInitializer#initialize() initialize()} method that has to be |
| 162 | * defined by concrete subclasses. The idea of {@link org.apache.commons.lang3.concurrent.BackgroundInitializer} is that |
| 163 | * it calls the {@code initialize()} method in a separate worker thread. An application creates a background initializer |
| 164 | * and starts it. Then it can continue with its work while the initializer runs in parallel. When the application needs |
| 165 | * the results of the initializer it calls its {@code get()} method. {@code get()} blocks until the initialization is |
| 166 | * complete. This is useful for instance at application startup. Here initialization steps (e.g. reading configuration |
| 167 | * files, opening a database connection, etc.) can be run in background threads while the application shows a splash |
| 168 | * screen and constructs its UI. |
| 169 | * </p> |
| 170 | * |
| 171 | * <p> |
| 172 | * As a concrete example consider an application that has to read the content of a URL - maybe a page with news - which |
| 173 | * is to be displayed to the user after login. Because loading the data over the network can take some time a |
| 174 | * specialized implementation of {@link org.apache.commons.lang3.concurrent.BackgroundInitializer} can be created for |
| 175 | * this purpose: |
| 176 | * </p> |
| 177 | * |
| 178 | * <pre>{@code |
| 179 | * public class URLLoader extends BackgroundInitializer<String> { |
| 180 | * // The URL to be loaded. |
| 181 | * private final URL url; |
| 182 | * |
| 183 | * public URLLoader(URL u) { |
| 184 | * url = u; |
| 185 | * } |
| 186 | * |
| 187 | * protected String initialize() throws ConcurrentException { |
| 188 | * try { |
| 189 | * InputStream in = url.openStream(); |
| 190 | * // read content into string |
| 191 | * ... |
| 192 | * return content; |
| 193 | * } catch (IOException ioex) { |
| 194 | * throw new ConcurrentException(ioex); |
| 195 | * } |
| 196 | * } |
| 197 | * } |
| 198 | * } |
| 199 | * </pre> |
| 200 | * |
| 201 | * <p> |
| 202 | * An application creates an instance of {@code URLLoader} and starts it. Then it can do other things. When it needs the |
| 203 | * content of the URL it calls the initializer's {@code get()} method: |
| 204 | * </p> |
| 205 | * |
| 206 | * <pre> |
| 207 | * <code> |
| 208 | * URL url = new URL("http://www.application-home-page.com/"); |
| 209 | * URLLoader loader = new URLLoader(url); |
| 210 | * loader.start(); // this starts the background initialization |
| 211 | * |
| 212 | * // do other stuff |
| 213 | * ... |
| 214 | * // now obtain the content of the URL |
| 215 | * String content; |
| 216 | * try { |
| 217 | * content = loader.get(); // this may block |
| 218 | * } catch (ConcurrentException cex) { |
| 219 | * content = "Error when loading URL " + url; |
| 220 | * } |
| 221 | * // display content |
| 222 | * </code> |
| 223 | * </pre> |
| 224 | * |
| 225 | * <p> |
| 226 | * Related to {@link org.apache.commons.lang3.concurrent.BackgroundInitializer} is the |
| 227 | * {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer} class. As the name implies, this class can |
| 228 | * handle multiple initializations in parallel. The basic usage scenario is that a |
| 229 | * {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer} instance is created. Then an arbitrary number |
| 230 | * of {@link org.apache.commons.lang3.concurrent.BackgroundInitializer} objects is added using the |
| 231 | * {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer#addInitializer(String, BackgroundInitializer)} |
| 232 | * method. When adding an initializer a string has to be provided which is later used to obtain the result for this |
| 233 | * initializer. When all initializers have been added the |
| 234 | * {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer#start()} method is called. This starts |
| 235 | * processing of all initializers. Later the {@code get()} method can be called. It waits until all initializers have |
| 236 | * finished their initialization. {@code get()} returns an object of type |
| 237 | * {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer.MultiBackgroundInitializerResults}. This object |
| 238 | * provides information about all initializations that have been performed. It can be checked whether a specific |
| 239 | * initializer was successful or threw an exception. Of course, all initialization results can be queried. |
| 240 | * </p> |
| 241 | * |
| 242 | * <p> |
| 243 | * With {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer} we can extend our example to perform |
| 244 | * multiple initialization steps. Suppose that in addition to loading a web site we also want to create a JPA entity |
| 245 | * manager factory and read a configuration file. We assume that corresponding |
| 246 | * {@link org.apache.commons.lang3.concurrent.BackgroundInitializer} implementations exist. The following example |
| 247 | * fragment shows the usage of {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer} for this purpose: |
| 248 | * </p> |
| 249 | * |
| 250 | * <pre> |
| 251 | * {@code |
| 252 | * MultiBackgroundInitializer initializer = new MultiBackgroundInitializer(); |
| 253 | * initializer.addInitializer("url", new URLLoader(url)); |
| 254 | * initializer.addInitializer("jpa", new JPAEMFInitializer()); |
| 255 | * initializer.addInitializer("config", new ConfigurationInitializer()); |
| 256 | * initializer.start(); // start background processing |
| 257 | * |
| 258 | * // do other interesting things in parallel |
| 259 | * ... |
| 260 | * // evaluate the results of background initialization |
| 261 | * MultiBackgroundInitializer.MultiBackgroundInitializerResults results = |
| 262 | * initializer.get(); |
| 263 | * String urlContent = (String) results.getResultObject("url"); |
| 264 | * EntityManagerFactory emf = |
| 265 | * (EntityManagerFactory) results.getResultObject("jpa"); |
| 266 | * ... |
| 267 | * } |
| 268 | * </pre> |
| 269 | * |
| 270 | * <p> |
| 271 | * The child initializers are added to the multi initializer and are assigned a unique name. The object returned by the |
| 272 | * {@code get()} method is then queried for the single results using these unique names. |
| 273 | * </p> |
| 274 | * |
| 275 | * <p> |
| 276 | * If background initializers - including {@link org.apache.commons.lang3.concurrent.MultiBackgroundInitializer} - are |
| 277 | * created using the standard constructor, they create their own {@link java.util.concurrent.ExecutorService} which is |
| 278 | * used behind the scenes to execute the worker tasks. It is also possible to pass in an |
| 279 | * {@link java.util.concurrent.ExecutorService} when the initializer is constructed. That way client code can configure |
| 280 | * the {@link java.util.concurrent.ExecutorService} according to its specific needs; for instance, the number of threads |
| 281 | * available could be limited. |
| 282 | * </p> |
| 283 | * |
| 284 | * <h2>Utility Classes</h2> |
| 285 | * |
| 286 | * <p> |
| 287 | * Another group of classes in the new {@code concurrent} package offers some generic functionality related to |
| 288 | * concurrency. There is the {@link org.apache.commons.lang3.concurrent.ConcurrentUtils} class with a bunch of static |
| 289 | * utility methods. One focus of this class is dealing with exceptions thrown by JDK classes. Many JDK classes of the |
| 290 | * executor framework throw exceptions of type {@link java.util.concurrent.ExecutionException} if something goes wrong. |
| 291 | * The root cause of these exceptions can also be a runtime exception or even an error. In typical Java programming you |
| 292 | * often do not want to deal with runtime exceptions directly; rather you let them fall through the hierarchy of method |
| 293 | * invocations until they reach a central exception handler. Checked exceptions in contrast are usually handled close to |
| 294 | * their occurrence. With {@link java.util.concurrent.ExecutionException} this principle is violated. Because it is a |
| 295 | * checked exception, an application is forced to handle it even if the cause is a runtime exception. So you typically |
| 296 | * have to inspect the cause of the {@link java.util.concurrent.ExecutionException} and test whether it is a checked |
| 297 | * exception which has to be handled. If this is not the case, the causing exception can be rethrown. |
| 298 | * </p> |
| 299 | * |
| 300 | * <p> |
| 301 | * The {@link org.apache.commons.lang3.concurrent.ConcurrentUtils#extractCause(java.util.concurrent.ExecutionException)} |
| 302 | * method does this work for you. It is passed an {@link java.util.concurrent.ExecutionException} and tests its root |
| 303 | * cause. If this is an error or a runtime exception, it is directly rethrown. Otherwise, an instance of |
| 304 | * {@link org.apache.commons.lang3.concurrent.ConcurrentException} is created and initialized with the root cause |
| 305 | * ({@link org.apache.commons.lang3.concurrent.ConcurrentException} is a new exception class in the |
| 306 | * {@code o.a.c.l.concurrent} package). So if you get such a |
| 307 | * {@link org.apache.commons.lang3.concurrent.ConcurrentException}, you can be sure that the original cause for the |
| 308 | * {@link java.util.concurrent.ExecutionException} was a checked exception. For users who prefer runtime exceptions in |
| 309 | * general there is also an |
| 310 | * {@link org.apache.commons.lang3.concurrent.ConcurrentUtils#extractCauseUnchecked(java.util.concurrent.ExecutionException)} |
| 311 | * method which behaves like {@code extractCause()}, but returns the unchecked exception |
| 312 | * {@link org.apache.commons.lang3.concurrent.ConcurrentRuntimeException} instead. |
| 313 | * </p> |
| 314 | * |
| 315 | * <p> |
| 316 | * In addition to the {@code extractCause()} methods there are corresponding |
| 317 | * {@link org.apache.commons.lang3.concurrent.ConcurrentUtils#handleCause(java.util.concurrent.ExecutionException)} and |
| 318 | * {@link org.apache.commons.lang3.concurrent.ConcurrentUtils#handleCauseUnchecked(java.util.concurrent.ExecutionException)} |
| 319 | * methods. These methods extract the cause of the passed in {@link java.util.concurrent.ExecutionException} and throw |
| 320 | * the resulting {@link org.apache.commons.lang3.concurrent.ConcurrentException} or |
| 321 | * {@link org.apache.commons.lang3.concurrent.ConcurrentRuntimeException}. This makes it easy to transform an |
| 322 | * {@link java.util.concurrent.ExecutionException} into a |
| 323 | * {@link org.apache.commons.lang3.concurrent.ConcurrentException} ignoring unchecked exceptions: |
| 324 | * </p> |
| 325 | * |
| 326 | * <pre>{@code |
| 327 | * Future<Object> future = ...; |
| 328 | * try { |
| 329 | * Object result = future.get(); |
| 330 | * ... |
| 331 | * } catch (ExecutionException eex) { |
| 332 | * ConcurrentUtils.handleCause(eex); |
| 333 | * } |
| 334 | * } |
| 335 | * </pre> |
| 336 | * |
| 337 | * <p> |
| 338 | * There is also some support for the concurrent initializers introduced in the last sub section. The |
| 339 | * {@code initialize()} method is passed a {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer} object and |
| 340 | * returns the object created by this initializer. It is null-safe. The {@code initializeUnchecked()} method works |
| 341 | * analogously, but a {@link org.apache.commons.lang3.concurrent.ConcurrentException} throws by the initializer is |
| 342 | * rethrown as a {@link org.apache.commons.lang3.concurrent.ConcurrentRuntimeException}. This is especially useful if |
| 343 | * the specific {@link org.apache.commons.lang3.concurrent.ConcurrentInitializer} does not throw checked exceptions. |
| 344 | * Using this method the code for requesting the object of an initializer becomes less verbose. The direct invocation |
| 345 | * looks as follows: |
| 346 | * </p> |
| 347 | * |
| 348 | * <pre>{@code |
| 349 | * ConcurrentInitializer<MyClass> initializer = ...; |
| 350 | * try { |
| 351 | * MyClass obj = initializer.get(); |
| 352 | * // do something with obj |
| 353 | * } catch (ConcurrentException cex) { |
| 354 | * // exception handling |
| 355 | * } |
| 356 | * } |
| 357 | * </pre> |
| 358 | * |
| 359 | * <p> |
| 360 | * Using the {@link org.apache.commons.lang3.concurrent.ConcurrentUtils#initializeUnchecked(ConcurrentInitializer)} |
| 361 | * method, this becomes: |
| 362 | * </p> |
| 363 | * |
| 364 | * <pre> |
| 365 | * {@code |
| 366 | * ConcurrentInitializer<MyClass> initializer = ...; |
| 367 | * MyClass obj = ConcurrentUtils.initializeUnchecked(initializer); |
| 368 | * // do something with obj |
| 369 | * } |
| 370 | * </pre> |
| 371 | * |
| 372 | * <p> |
| 373 | * Another utility class deals with the creation of threads. When using the <em>Executor</em> framework new in JDK 1.5 |
| 374 | * the developer usually does not have to care about creating threads; the executors create the threads they need on |
| 375 | * demand. However, sometimes it is desired to set some properties of the newly created worker threads. This is possible |
| 376 | * through the {@link java.util.concurrent.ThreadFactory} interface; an implementation of this interface has to be |
| 377 | * created and passed to an executor on creation time. Currently, the JDK does not provide an implementation of |
| 378 | * {@link java.util.concurrent.ThreadFactory}, so one has to start from scratch. |
| 379 | * </p> |
| 380 | * |
| 381 | * <p> |
| 382 | * With {@link org.apache.commons.lang3.concurrent.BasicThreadFactory} Commons Lang has an implementation of |
| 383 | * {@link java.util.concurrent.ThreadFactory} that works out of the box for many common use cases. For instance, it is |
| 384 | * possible to set a naming pattern for the new threads, set the daemon flag and a priority, or install a handler for |
| 385 | * uncaught exceptions. Instances of {@link org.apache.commons.lang3.concurrent.BasicThreadFactory} are created and |
| 386 | * configured using the nested {@link org.apache.commons.lang3.concurrent.BasicThreadFactory.Builder} class. The |
| 387 | * following example shows a typical usage scenario: |
| 388 | * </p> |
| 389 | * |
| 390 | * <pre> |
| 391 | * {@code |
| 392 | * BasicThreadFactory factory = new BasicThreadFactory.Builder() |
| 393 | * .namingPattern("worker-thread-%d") |
| 394 | * .daemon(true) |
| 395 | * .uncaughtExceptionHandler(myHandler) |
| 396 | * .build(); |
| 397 | * ExecutorService exec = Executors.newSingleThreadExecutor(factory); |
| 398 | * } |
| 399 | * </pre> |
| 400 | * |
| 401 | * <p> |
| 402 | * The nested {@link org.apache.commons.lang3.concurrent.BasicThreadFactory.Builder} class defines some methods for |
| 403 | * configuring the new {@link org.apache.commons.lang3.concurrent.BasicThreadFactory} instance. Objects of this class |
| 404 | * are immutable, so these attributes cannot be changed later. The naming pattern is a string which can be passed to |
| 405 | * {@link String#format(java.util.Locale, String, Object...)}. The placeholder <em>%d</em> is replaced by an |
| 406 | * increasing counter value. An instance can wrap another {@link java.util.concurrent.ThreadFactory} implementation; |
| 407 | * this is achieved by calling the builder's |
| 408 | * {@link org.apache.commons.lang3.concurrent.BasicThreadFactory.Builder#wrappedFactory(java.util.concurrent.ThreadFactory) |
| 409 | * wrappedFactory(ThreadFactory)} method. This factory is then used for creating new threads; after that the specific |
| 410 | * attributes are applied to the new thread. If no wrapped factory is set, the default factory provided by the JDK is |
| 411 | * used. |
| 412 | * </p> |
| 413 | * |
| 414 | * <h2>Synchronization objects</h2> |
| 415 | * |
| 416 | * <p> |
| 417 | * The {@code concurrent} package also provides some support for specific synchronization problems with threads. |
| 418 | * </p> |
| 419 | * |
| 420 | * <p> |
| 421 | * {@link org.apache.commons.lang3.concurrent.TimedSemaphore} allows restricted access to a resource in a given time |
| 422 | * frame. Similar to a semaphore, a number of permits can be acquired. What is new is the fact that the permits |
| 423 | * available are related to a given time unit. For instance, the timed semaphore can be configured to allow 10 permits |
| 424 | * in a second. Now multiple threads access the semaphore and call its |
| 425 | * {@link org.apache.commons.lang3.concurrent.TimedSemaphore#acquire()} method. The semaphore keeps track about the |
| 426 | * number of granted permits in the current time frame. Only 10 calls are allowed; if there are further callers, they |
| 427 | * are blocked until the time frame (one second in this example) is over. Then all blocking threads are released, and |
| 428 | * the counter of available permits is reset to 0. So the game can start anew. |
| 429 | * </p> |
| 430 | * |
| 431 | * <p> |
| 432 | * What are use cases for {@link org.apache.commons.lang3.concurrent.TimedSemaphore}? One example is to artificially |
| 433 | * limit the load produced by multiple threads. Consider a batch application accessing a database to extract statistical |
| 434 | * data. The application runs multiple threads which issue database queries in parallel and perform some calculation on |
| 435 | * the results. If the database to be processed is huge and is also used by a production system, multiple factors have |
| 436 | * to be balanced: On one hand, the time required for the statistical evaluation should not take too long. Therefore you |
| 437 | * will probably use a larger number of threads because most of its life time a thread will just wait for the database |
| 438 | * to return query results. On the other hand, the load on the database generated by all these threads should be limited |
| 439 | * so that the responsiveness of the production system is not affected. With a |
| 440 | * {@link org.apache.commons.lang3.concurrent.TimedSemaphore} object this can be achieved. The semaphore can be |
| 441 | * configured to allow e.g. 100 queries per second. After these queries have been sent to the database the threads have |
| 442 | * to wait until the second is over - then they can query again. By fine-tuning the limit enforced by the semaphore a |
| 443 | * good balance between performance and database load can be established. It is even possible to chang? the number of |
| 444 | * available permits at runtime. So this number can be reduced during the typical working hours and increased at night. |
| 445 | * </p> |
| 446 | * |
| 447 | * <p> |
| 448 | * The following code examples demonstrate parts of the implementation of such a scenario. First the batch application |
| 449 | * has to create an instance of {@link org.apache.commons.lang3.concurrent.TimedSemaphore} and to initialize its |
| 450 | * properties with default values: |
| 451 | * </p> |
| 452 | * |
| 453 | * {@code TimedSemaphore semaphore = new TimedSemaphore(1, TimeUnit.SECONDS, 100);} |
| 454 | * |
| 455 | * <p> |
| 456 | * Here we specify that the semaphore should allow 100 permits in one second. This is effectively the limit of database |
| 457 | * queries per second in our example use case. Next the server threads issuing database queries and performing |
| 458 | * statistical operations can be initialized. They are passed a reference to the semaphore at creation time. Before they |
| 459 | * execute a query they have to acquire a permit. |
| 460 | * </p> |
| 461 | * |
| 462 | * <pre> |
| 463 | * <code> |
| 464 | * public class StatisticsTask implements Runnable { |
| 465 | * // The semaphore for limiting database load. |
| 466 | * private final TimedSemaphore semaphore; |
| 467 | * |
| 468 | * public StatisticsTask(TimedSemaphore sem, Connection con) { |
| 469 | * semaphore = sem; |
| 470 | * ... |
| 471 | * } |
| 472 | * |
| 473 | * //The main processing method. Executes queries and evaluates their results. |
| 474 | * public void run() { |
| 475 | * try { |
| 476 | * while (!isDone()) { |
| 477 | * semaphore.acquire(); // enforce the load limit |
| 478 | * executeAndEvaluateQuery(); |
| 479 | * } |
| 480 | * } catch (InterruptedException iex) { |
| 481 | * // fall through |
| 482 | * } |
| 483 | * } |
| 484 | * } |
| 485 | * </code> |
| 486 | * </pre> |
| 487 | * |
| 488 | * <p> |
| 489 | * The important line here is the call to {@code semaphore.acquire()}. If the number of permits in the current time |
| 490 | * frame has not yet been reached, the call returns immediately. Otherwise, it blocks until the end of the time frame. |
| 491 | * The last piece missing is a scheduler service which adapts the number of permits allowed by the semaphore according |
| 492 | * to the time of day. We assume that this service is pretty simple and knows only two different time slots: working |
| 493 | * shift and night shift. The service is triggered periodically. It then determines the current time slot and configures |
| 494 | * the timed semaphore accordingly. |
| 495 | * </p> |
| 496 | * |
| 497 | * <pre> |
| 498 | * <code> |
| 499 | * public class SchedulerService { |
| 500 | * // The semaphore for limiting database load. |
| 501 | * private final TimedSemaphore semaphore; |
| 502 | * ... |
| 503 | * |
| 504 | * // Configures the timed semaphore based on the current time of day. This method is called periodically. |
| 505 | * public void configureTimedSemaphore() { |
| 506 | * int limit; |
| 507 | * if (isWorkshift()) { |
| 508 | * limit = 50; // low database load |
| 509 | * } else { |
| 510 | * limit = 250; // high database load |
| 511 | * } |
| 512 | * |
| 513 | * semaphore.setLimit(limit); |
| 514 | * } |
| 515 | * } |
| 516 | * </code> |
| 517 | * </pre> |
| 518 | * |
| 519 | * <p> |
| 520 | * With the {@link org.apache.commons.lang3.concurrent.TimedSemaphore#setLimit(int)} method the number of permits |
| 521 | * allowed for a time frame can be changed. There are some other methods for querying the internal state of a timed |
| 522 | * semaphore. Also some statistical data is available, e.g. the average number of {@code acquire()} calls per time |
| 523 | * frame. When a timed semaphore is no more needed, its {@code shutdown()} method has to be called. |
| 524 | * </p> |
| 525 | */ |
| 526 | package org.apache.commons.lang3.concurrent; |