001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.lang3.concurrent;
018
019 import java.util.Collections;
020 import java.util.HashMap;
021 import java.util.Map;
022 import java.util.NoSuchElementException;
023 import java.util.Set;
024 import java.util.concurrent.ExecutorService;
025
026 /**
027 * <p>
028 * A specialized {@link BackgroundInitializer} implementation that can deal with
029 * multiple background initialization tasks.
030 * </p>
031 * <p>
032 * This class has a similar purpose as {@link BackgroundInitializer}. However,
033 * it is not limited to a single background initialization task. Rather it
034 * manages an arbitrary number of {@code BackgroundInitializer} objects,
035 * executes them, and waits until they are completely initialized. This is
036 * useful for applications that have to perform multiple initialization tasks
037 * that can run in parallel (i.e. that do not depend on each other). This class
038 * takes care about the management of an {@code ExecutorService} and shares it
039 * with the {@code BackgroundInitializer} objects it is responsible for; so the
040 * using application need not bother with these details.
041 * </p>
042 * <p>
043 * The typical usage scenario for {@code MultiBackgroundInitializer} is as
044 * follows:
045 * <ul>
046 * <li>Create a new instance of the class. Optionally pass in a pre-configured
047 * {@code ExecutorService}. Alternatively {@code MultiBackgroundInitializer} can
048 * create a temporary {@code ExecutorService} and delete it after initialization
049 * is complete.</li>
050 * <li>Create specialized {@link BackgroundInitializer} objects for the
051 * initialization tasks to be performed and add them to the {@code
052 * MultiBackgroundInitializer} using the
053 * {@link #addInitializer(String, BackgroundInitializer)} method.</li>
054 * <li>After all initializers have been added, call the {@link #start()} method.
055 * </li>
056 * <li>When access to the result objects produced by the {@code
057 * BackgroundInitializer} objects is needed call the {@link #get()} method. The
058 * object returned here provides access to all result objects created during
059 * initialization. It also stores information about exceptions that have
060 * occurred.</li>
061 * </ul>
062 * </p>
063 * <p>
064 * {@code MultiBackgroundInitializer} starts a special controller task that
065 * starts all {@code BackgroundInitializer} objects added to the instance.
066 * Before the an initializer is started it is checked whether this initializer
067 * already has an {@code ExecutorService} set. If this is the case, this {@code
068 * ExecutorService} is used for running the background task. Otherwise the
069 * current {@code ExecutorService} of this {@code MultiBackgroundInitializer} is
070 * shared with the initializer.
071 * </p>
072 * <p>
073 * The easiest way of using this class is to let it deal with the management of
074 * an {@code ExecutorService} itself: If no external {@code ExecutorService} is
075 * provided, the class creates a temporary {@code ExecutorService} (that is
076 * capable of executing all background tasks in parallel) and destroys it at the
077 * end of background processing.
078 * </p>
079 * <p>
080 * Alternatively an external {@code ExecutorService} can be provided - either at
081 * construction time or later by calling the
082 * {@link #setExternalExecutor(ExecutorService)} method. In this case all
083 * background tasks are scheduled at this external {@code ExecutorService}.
084 * <strong>Important note:</strong> When using an external {@code
085 * ExecutorService} be sure that the number of threads managed by the service is
086 * large enough. Otherwise a deadlock can happen! This is the case in the
087 * following scenario: {@code MultiBackgroundInitializer} starts a task that
088 * starts all registered {@code BackgroundInitializer} objects and waits for
089 * their completion. If for instance a single threaded {@code ExecutorService}
090 * is used, none of the background tasks can be executed, and the task created
091 * by {@code MultiBackgroundInitializer} waits forever.
092 * </p>
093 *
094 * @since 3.0
095 * @version $Id: MultiBackgroundInitializer.java 1082301 2011-03-16 21:02:15Z oheger $
096 */
097 public class MultiBackgroundInitializer
098 extends
099 BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> {
100 /** A map with the child initializers. */
101 private final Map<String, BackgroundInitializer<?>> childInitializers =
102 new HashMap<String, BackgroundInitializer<?>>();
103
104 /**
105 * Creates a new instance of {@code MultiBackgroundInitializer}.
106 */
107 public MultiBackgroundInitializer() {
108 super();
109 }
110
111 /**
112 * Creates a new instance of {@code MultiBackgroundInitializer} and
113 * initializes it with the given external {@code ExecutorService}.
114 *
115 * @param exec the {@code ExecutorService} for executing the background
116 * tasks
117 */
118 public MultiBackgroundInitializer(ExecutorService exec) {
119 super(exec);
120 }
121
122 /**
123 * Adds a new {@code BackgroundInitializer} to this object. When this
124 * {@code MultiBackgroundInitializer} is started, the given initializer will
125 * be processed. This method must not be called after {@link #start()} has
126 * been invoked.
127 *
128 * @param name the name of the initializer (must not be <b>null</b>)
129 * @param init the {@code BackgroundInitializer} to add (must not be
130 * <b>null</b>)
131 * @throws IllegalArgumentException if a required parameter is missing
132 * @throws IllegalStateException if {@code start()} has already been called
133 */
134 public void addInitializer(String name, BackgroundInitializer<?> init) {
135 if (name == null) {
136 throw new IllegalArgumentException(
137 "Name of child initializer must not be null!");
138 }
139 if (init == null) {
140 throw new IllegalArgumentException(
141 "Child initializer must not be null!");
142 }
143
144 synchronized (this) {
145 if (isStarted()) {
146 throw new IllegalStateException(
147 "addInitializer() must not be called after start()!");
148 }
149 childInitializers.put(name, init);
150 }
151 }
152
153 /**
154 * Returns the number of tasks needed for executing all child {@code
155 * BackgroundInitializer} objects in parallel. This implementation sums up
156 * the required tasks for all child initializers (which is necessary if one
157 * of the child initializers is itself a {@code MultiBackgroundInitializer}
158 * ). Then it adds 1 for the control task that waits for the completion of
159 * the children.
160 *
161 * @return the number of tasks required for background processing
162 */
163 @Override
164 protected int getTaskCount() {
165 int result = 1;
166
167 for (BackgroundInitializer<?> bi : childInitializers.values()) {
168 result += bi.getTaskCount();
169 }
170
171 return result;
172 }
173
174 /**
175 * Creates the results object. This implementation starts all child {@code
176 * BackgroundInitializer} objects. Then it collects their results and
177 * creates a {@code MultiBackgroundInitializerResults} object with this
178 * data. If a child initializer throws a checked exceptions, it is added to
179 * the results object. Unchecked exceptions are propagated.
180 *
181 * @return the results object
182 * @throws Exception if an error occurs
183 */
184 @Override
185 protected MultiBackgroundInitializerResults initialize() throws Exception {
186 Map<String, BackgroundInitializer<?>> inits;
187 synchronized (this) {
188 // create a snapshot to operate on
189 inits = new HashMap<String, BackgroundInitializer<?>>(
190 childInitializers);
191 }
192
193 // start the child initializers
194 ExecutorService exec = getActiveExecutor();
195 for (BackgroundInitializer<?> bi : inits.values()) {
196 if (bi.getExternalExecutor() == null) {
197 // share the executor service if necessary
198 bi.setExternalExecutor(exec);
199 }
200 bi.start();
201 }
202
203 // collect the results
204 Map<String, Object> results = new HashMap<String, Object>();
205 Map<String, ConcurrentException> excepts = new HashMap<String, ConcurrentException>();
206 for (Map.Entry<String, BackgroundInitializer<?>> e : inits.entrySet()) {
207 try {
208 results.put(e.getKey(), e.getValue().get());
209 } catch (ConcurrentException cex) {
210 excepts.put(e.getKey(), cex);
211 }
212 }
213
214 return new MultiBackgroundInitializerResults(inits, results, excepts);
215 }
216
217 /**
218 * A data class for storing the results of the background initialization
219 * performed by {@code MultiBackgroundInitializer}. Objects of this inner
220 * class are returned by {@link MultiBackgroundInitializer#initialize()}.
221 * They allow access to all result objects produced by the
222 * {@link BackgroundInitializer} objects managed by the owning instance. It
223 * is also possible to retrieve status information about single
224 * {@link BackgroundInitializer}s, i.e. whether they completed normally or
225 * caused an exception.
226 */
227 public static class MultiBackgroundInitializerResults {
228 /** A map with the child initializers. */
229 private final Map<String, BackgroundInitializer<?>> initializers;
230
231 /** A map with the result objects. */
232 private final Map<String, Object> resultObjects;
233
234 /** A map with the exceptions. */
235 private final Map<String, ConcurrentException> exceptions;
236
237 /**
238 * Creates a new instance of {@code MultiBackgroundInitializerResults}
239 * and initializes it with maps for the {@code BackgroundInitializer}
240 * objects, their result objects and the exceptions thrown by them.
241 *
242 * @param inits the {@code BackgroundInitializer} objects
243 * @param results the result objects
244 * @param excepts the exceptions
245 */
246 private MultiBackgroundInitializerResults(
247 Map<String, BackgroundInitializer<?>> inits,
248 Map<String, Object> results,
249 Map<String, ConcurrentException> excepts) {
250 initializers = inits;
251 resultObjects = results;
252 exceptions = excepts;
253 }
254
255 /**
256 * Returns the {@code BackgroundInitializer} with the given name. If the
257 * name cannot be resolved, an exception is thrown.
258 *
259 * @param name the name of the {@code BackgroundInitializer}
260 * @return the {@code BackgroundInitializer} with this name
261 * @throws NoSuchElementException if the name cannot be resolved
262 */
263 public BackgroundInitializer<?> getInitializer(String name) {
264 return checkName(name);
265 }
266
267 /**
268 * Returns the result object produced by the {@code
269 * BackgroundInitializer} with the given name. This is the object
270 * returned by the initializer's {@code initialize()} method. If this
271 * {@code BackgroundInitializer} caused an exception, <b>null</b> is
272 * returned. If the name cannot be resolved, an exception is thrown.
273 *
274 * @param name the name of the {@code BackgroundInitializer}
275 * @return the result object produced by this {@code
276 * BackgroundInitializer}
277 * @throws NoSuchElementException if the name cannot be resolved
278 */
279 public Object getResultObject(String name) {
280 checkName(name);
281 return resultObjects.get(name);
282 }
283
284 /**
285 * Returns a flag whether the {@code BackgroundInitializer} with the
286 * given name caused an exception.
287 *
288 * @param name the name of the {@code BackgroundInitializer}
289 * @return a flag whether this initializer caused an exception
290 * @throws NoSuchElementException if the name cannot be resolved
291 */
292 public boolean isException(String name) {
293 checkName(name);
294 return exceptions.containsKey(name);
295 }
296
297 /**
298 * Returns the {@code ConcurrentException} object that was thrown by the
299 * {@code BackgroundInitializer} with the given name. If this
300 * initializer did not throw an exception, the return value is
301 * <b>null</b>. If the name cannot be resolved, an exception is thrown.
302 *
303 * @param name the name of the {@code BackgroundInitializer}
304 * @return the exception thrown by this initializer
305 * @throws NoSuchElementException if the name cannot be resolved
306 */
307 public ConcurrentException getException(String name) {
308 checkName(name);
309 return exceptions.get(name);
310 }
311
312 /**
313 * Returns a set with the names of all {@code BackgroundInitializer}
314 * objects managed by the {@code MultiBackgroundInitializer}.
315 *
316 * @return an (unmodifiable) set with the names of the managed {@code
317 * BackgroundInitializer} objects
318 */
319 public Set<String> initializerNames() {
320 return Collections.unmodifiableSet(initializers.keySet());
321 }
322
323 /**
324 * Returns a flag whether the whole initialization was successful. This
325 * is the case if no child initializer has thrown an exception.
326 *
327 * @return a flag whether the initialization was successful
328 */
329 public boolean isSuccessful() {
330 return exceptions.isEmpty();
331 }
332
333 /**
334 * Checks whether an initializer with the given name exists. If not,
335 * throws an exception. If it exists, the associated child initializer
336 * is returned.
337 *
338 * @param name the name to check
339 * @return the initializer with this name
340 * @throws NoSuchElementException if the name is unknown
341 */
342 private BackgroundInitializer<?> checkName(String name) {
343 BackgroundInitializer<?> init = initializers.get(name);
344 if (init == null) {
345 throw new NoSuchElementException(
346 "No child initializer with name " + name);
347 }
348
349 return init;
350 }
351 }
352 }