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