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