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 */
017package org.apache.commons.lang3.concurrent;
018
019import java.util.Collections;
020import java.util.HashMap;
021import java.util.Map;
022import java.util.NoSuchElementException;
023import java.util.Set;
024import 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 * </p>
046 * <ul>
047 * <li>Create a new instance of the class. Optionally pass in a pre-configured
048 * {@code ExecutorService}. Alternatively {@code MultiBackgroundInitializer} can
049 * create a temporary {@code ExecutorService} and delete it after initialization
050 * is complete.</li>
051 * <li>Create specialized {@link BackgroundInitializer} objects for the
052 * initialization tasks to be performed and add them to the {@code
053 * MultiBackgroundInitializer} using the
054 * {@link #addInitializer(String, BackgroundInitializer)} method.</li>
055 * <li>After all initializers have been added, call the {@link #start()} method.
056 * </li>
057 * <li>When access to the result objects produced by the {@code
058 * BackgroundInitializer} objects is needed call the {@link #get()} method. The
059 * object returned here provides access to all result objects created during
060 * initialization. It also stores information about exceptions that have
061 * occurred.</li>
062 * </ul>
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 */
096public class MultiBackgroundInitializer
097        extends
098        BackgroundInitializer<MultiBackgroundInitializer.MultiBackgroundInitializerResults> {
099    /** A map with the child initializers. */
100    private final Map<String, BackgroundInitializer<?>> childInitializers =
101        new HashMap<String, BackgroundInitializer<?>>();
102
103    /**
104     * Creates a new instance of {@code MultiBackgroundInitializer}.
105     */
106    public MultiBackgroundInitializer() {
107        super();
108    }
109
110    /**
111     * Creates a new instance of {@code MultiBackgroundInitializer} and
112     * initializes it with the given external {@code ExecutorService}.
113     *
114     * @param exec the {@code ExecutorService} for executing the background
115     * tasks
116     */
117    public MultiBackgroundInitializer(final ExecutorService exec) {
118        super(exec);
119    }
120
121    /**
122     * Adds a new {@code BackgroundInitializer} to this object. When this
123     * {@code MultiBackgroundInitializer} is started, the given initializer will
124     * be processed. This method must not be called after {@link #start()} has
125     * been invoked.
126     *
127     * @param name the name of the initializer (must not be <b>null</b>)
128     * @param init the {@code BackgroundInitializer} to add (must not be
129     * <b>null</b>)
130     * @throws IllegalArgumentException if a required parameter is missing
131     * @throws IllegalStateException if {@code start()} has already been called
132     */
133    public void addInitializer(final String name, final BackgroundInitializer<?> init) {
134        if (name == null) {
135            throw new IllegalArgumentException(
136                    "Name of child initializer must not be null!");
137        }
138        if (init == null) {
139            throw new IllegalArgumentException(
140                    "Child initializer must not be null!");
141        }
142
143        synchronized (this) {
144            if (isStarted()) {
145                throw new IllegalStateException(
146                        "addInitializer() must not be called after start()!");
147            }
148            childInitializers.put(name, init);
149        }
150    }
151
152    /**
153     * Returns the number of tasks needed for executing all child {@code
154     * BackgroundInitializer} objects in parallel. This implementation sums up
155     * the required tasks for all child initializers (which is necessary if one
156     * of the child initializers is itself a {@code MultiBackgroundInitializer}
157     * ). Then it adds 1 for the control task that waits for the completion of
158     * the children.
159     *
160     * @return the number of tasks required for background processing
161     */
162    @Override
163    protected int getTaskCount() {
164        int result = 1;
165
166        for (final BackgroundInitializer<?> bi : childInitializers.values()) {
167            result += bi.getTaskCount();
168        }
169
170        return result;
171    }
172
173    /**
174     * Creates the results object. This implementation starts all child {@code
175     * BackgroundInitializer} objects. Then it collects their results and
176     * creates a {@code MultiBackgroundInitializerResults} object with this
177     * data. If a child initializer throws a checked exceptions, it is added to
178     * the results object. Unchecked exceptions are propagated.
179     *
180     * @return the results object
181     * @throws Exception if an error occurs
182     */
183    @Override
184    protected MultiBackgroundInitializerResults initialize() throws Exception {
185        Map<String, BackgroundInitializer<?>> inits;
186        synchronized (this) {
187            // create a snapshot to operate on
188            inits = new HashMap<String, BackgroundInitializer<?>>(
189                    childInitializers);
190        }
191
192        // start the child initializers
193        final ExecutorService exec = getActiveExecutor();
194        for (final BackgroundInitializer<?> bi : inits.values()) {
195            if (bi.getExternalExecutor() == null) {
196                // share the executor service if necessary
197                bi.setExternalExecutor(exec);
198            }
199            bi.start();
200        }
201
202        // collect the results
203        final Map<String, Object> results = new HashMap<String, Object>();
204        final Map<String, ConcurrentException> excepts = new HashMap<String, ConcurrentException>();
205        for (final Map.Entry<String, BackgroundInitializer<?>> e : inits.entrySet()) {
206            try {
207                results.put(e.getKey(), e.getValue().get());
208            } catch (final ConcurrentException cex) {
209                excepts.put(e.getKey(), cex);
210            }
211        }
212
213        return new MultiBackgroundInitializerResults(inits, results, excepts);
214    }
215
216    /**
217     * A data class for storing the results of the background initialization
218     * performed by {@code MultiBackgroundInitializer}. Objects of this inner
219     * class are returned by {@link MultiBackgroundInitializer#initialize()}.
220     * They allow access to all result objects produced by the
221     * {@link BackgroundInitializer} objects managed by the owning instance. It
222     * is also possible to retrieve status information about single
223     * {@link BackgroundInitializer}s, i.e. whether they completed normally or
224     * caused an exception.
225     */
226    public static class MultiBackgroundInitializerResults {
227        /** A map with the child initializers. */
228        private final Map<String, BackgroundInitializer<?>> initializers;
229
230        /** A map with the result objects. */
231        private final Map<String, Object> resultObjects;
232
233        /** A map with the exceptions. */
234        private final Map<String, ConcurrentException> exceptions;
235
236        /**
237         * Creates a new instance of {@code MultiBackgroundInitializerResults}
238         * and initializes it with maps for the {@code BackgroundInitializer}
239         * objects, their result objects and the exceptions thrown by them.
240         *
241         * @param inits the {@code BackgroundInitializer} objects
242         * @param results the result objects
243         * @param excepts the exceptions
244         */
245        private MultiBackgroundInitializerResults(
246                final Map<String, BackgroundInitializer<?>> inits,
247                final Map<String, Object> results,
248                final Map<String, ConcurrentException> excepts) {
249            initializers = inits;
250            resultObjects = results;
251            exceptions = excepts;
252        }
253
254        /**
255         * Returns the {@code BackgroundInitializer} with the given name. If the
256         * name cannot be resolved, an exception is thrown.
257         *
258         * @param name the name of the {@code BackgroundInitializer}
259         * @return the {@code BackgroundInitializer} with this name
260         * @throws NoSuchElementException if the name cannot be resolved
261         */
262        public BackgroundInitializer<?> getInitializer(final String name) {
263            return checkName(name);
264        }
265
266        /**
267         * Returns the result object produced by the {@code
268         * BackgroundInitializer} with the given name. This is the object
269         * returned by the initializer's {@code initialize()} method. If this
270         * {@code BackgroundInitializer} caused an exception, <b>null</b> is
271         * returned. If the name cannot be resolved, an exception is thrown.
272         *
273         * @param name the name of the {@code BackgroundInitializer}
274         * @return the result object produced by this {@code
275         * BackgroundInitializer}
276         * @throws NoSuchElementException if the name cannot be resolved
277         */
278        public Object getResultObject(final String name) {
279            checkName(name);
280            return resultObjects.get(name);
281        }
282
283        /**
284         * Returns a flag whether the {@code BackgroundInitializer} with the
285         * given name caused an exception.
286         *
287         * @param name the name of the {@code BackgroundInitializer}
288         * @return a flag whether this initializer caused an exception
289         * @throws NoSuchElementException if the name cannot be resolved
290         */
291        public boolean isException(final String name) {
292            checkName(name);
293            return exceptions.containsKey(name);
294        }
295
296        /**
297         * Returns the {@code ConcurrentException} object that was thrown by the
298         * {@code BackgroundInitializer} with the given name. If this
299         * initializer did not throw an exception, the return value is
300         * <b>null</b>. If the name cannot be resolved, an exception is thrown.
301         *
302         * @param name the name of the {@code BackgroundInitializer}
303         * @return the exception thrown by this initializer
304         * @throws NoSuchElementException if the name cannot be resolved
305         */
306        public ConcurrentException getException(final String name) {
307            checkName(name);
308            return exceptions.get(name);
309        }
310
311        /**
312         * Returns a set with the names of all {@code BackgroundInitializer}
313         * objects managed by the {@code MultiBackgroundInitializer}.
314         *
315         * @return an (unmodifiable) set with the names of the managed {@code
316         * BackgroundInitializer} objects
317         */
318        public Set<String> initializerNames() {
319            return Collections.unmodifiableSet(initializers.keySet());
320        }
321
322        /**
323         * Returns a flag whether the whole initialization was successful. This
324         * is the case if no child initializer has thrown an exception.
325         *
326         * @return a flag whether the initialization was successful
327         */
328        public boolean isSuccessful() {
329            return exceptions.isEmpty();
330        }
331
332        /**
333         * Checks whether an initializer with the given name exists. If not,
334         * throws an exception. If it exists, the associated child initializer
335         * is returned.
336         *
337         * @param name the name to check
338         * @return the initializer with this name
339         * @throws NoSuchElementException if the name is unknown
340         */
341        private BackgroundInitializer<?> checkName(final String name) {
342            final BackgroundInitializer<?> init = initializers.get(name);
343            if (init == null) {
344                throw new NoSuchElementException(
345                        "No child initializer with name " + name);
346            }
347
348            return init;
349        }
350    }
351}