Source code
Description: source: package: org.apache.commons.lang3.concurrent, class: ConcurrentUtils

    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 *      https://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.concurrent.ConcurrentMap;
    020import java.util.concurrent.ExecutionException;
    021import java.util.concurrent.Future;
    022import java.util.concurrent.TimeUnit;
    023
    024import org.apache.commons.lang3.Validate;
    025import org.apache.commons.lang3.exception.ExceptionUtils;
    026
    027/**
    028 * A utility class providing functionality related to the {@code
    029 * java.util.concurrent} package.
    030 *
    031 * @since 3.0
    032 */
    033public class ConcurrentUtils {
    034
    035    /**
    036     * A specialized {@link Future} implementation which wraps a constant value.
    037     * @param <T> the type of the value wrapped by this class
    038     */
    039    static final class ConstantFuture<T> implements Future<T> {
    040        /** The constant value. */
    041        private final T value;
    042
    043        /**
    044         * Creates a new instance of {@link ConstantFuture} and initializes it
    045         * with the constant value.
    046         *
    047         * @param value the value (may be <strong>null</strong>)
    048         */
    049        ConstantFuture(final T value) {
    050            this.value = value;
    051        }
    052
    053        /**
    054         * {@inheritDoc} The cancel operation is not supported. This
    055         * implementation always returns <strong>false</strong>.
    056         */
    057        @Override
    058        public boolean cancel(final boolean mayInterruptIfRunning) {
    059            return false;
    060        }
    061
    062        /**
    063         * {@inheritDoc} This implementation just returns the constant value.
    064         */
    065        @Override
    066        public T get() {
    067            return value;
    068        }
    069
    070        /**
    071         * {@inheritDoc} This implementation just returns the constant value; it
    072         * does not block, therefore the timeout has no meaning.
    073         */
    074        @Override
    075        public T get(final long timeout, final TimeUnit unit) {
    076            return value;
    077        }
    078
    079        /**
    080         * {@inheritDoc} This implementation always returns <strong>false</strong>; there
    081         * is no background process which could be cancelled.
    082         */
    083        @Override
    084        public boolean isCancelled() {
    085            return false;
    086        }
    087
    088        /**
    089         * {@inheritDoc} This implementation always returns <strong>true</strong> because
    090         * the constant object managed by this {@link Future} implementation is
    091         * always available.
    092         */
    093        @Override
    094        public boolean isDone() {
    095            return true;
    096        }
    097    }
    098
    099    /**
    100     * Tests whether the specified {@link Throwable} is a checked exception. If
    101     * not, an exception is thrown.
    102     *
    103     * @param ex the {@link Throwable} to check
    104     * @return a flag whether the passed in exception is a checked exception
    105     * @throws IllegalArgumentException if the {@link Throwable} is not a
    106     * checked exception
    107     */
    108    static Throwable checkedException(final Throwable ex) {
    109        Validate.isTrue(ExceptionUtils.isChecked(ex), "Not a checked exception: %s", ex);
    110        return ex;
    111    }
    112
    113    /**
    114     * Gets an implementation of {@link Future} that is immediately done
    115     * and returns the specified constant value.
    116     *
    117     * <p>
    118     * This can be useful to return a simple constant immediately from the
    119     * concurrent processing, perhaps as part of avoiding nulls.
    120     * A constant future can also be useful in testing.
    121     * </p>
    122     *
    123     * @param <T> the type of the value used by this {@link Future} object
    124     * @param value  the constant value to return, may be null
    125     * @return an instance of Future that will return the value, never null
    126     */
    127    public static <T> Future<T> constantFuture(final T value) {
    128        return new ConstantFuture<>(value);
    129    }
    130
    131    /**
    132     * Checks if a concurrent map contains a key and creates a corresponding
    133     * value if not. This method first checks the presence of the key in the
    134     * given map. If it is already contained, its value is returned. Otherwise
    135     * the {@code get()} method of the passed in {@link ConcurrentInitializer}
    136     * is called. With the resulting object
    137     * {@link #putIfAbsent(ConcurrentMap, Object, Object)} is called. This
    138     * handles the case that in the meantime another thread has added the key to
    139     * the map. Both the map and the initializer can be <strong>null</strong>; in this
    140     * case this method simply returns <strong>null</strong>.
    141     *
    142     * @param <K> the type of the keys of the map
    143     * @param <V> the type of the values of the map
    144     * @param map the map to be modified
    145     * @param key the key of the value to be added
    146     * @param init the {@link ConcurrentInitializer} for creating the value
    147     * @return the value stored in the map after this operation; this may or may
    148     * not be the object created by the {@link ConcurrentInitializer}
    149     * @throws ConcurrentException if the initializer throws an exception
    150     */
    151    public static <K, V> V createIfAbsent(final ConcurrentMap<K, V> map, final K key,
    152            final ConcurrentInitializer<V> init) throws ConcurrentException {
    153        if (map == null || init == null) {
    154            return null;
    155        }
    156
    157        final V value = map.get(key);
    158        if (value == null) {
    159            return putIfAbsent(map, key, init.get());
    160        }
    161        return value;
    162    }
    163
    164    /**
    165     * Checks if a concurrent map contains a key and creates a corresponding
    166     * value if not, suppressing checked exceptions. This method calls
    167     * {@code createIfAbsent()}. If a {@link ConcurrentException} is thrown, it
    168     * is caught and re-thrown as a {@link ConcurrentRuntimeException}.
    169     *
    170     * @param <K> the type of the keys of the map
    171     * @param <V> the type of the values of the map
    172     * @param map the map to be modified
    173     * @param key the key of the value to be added
    174     * @param init the {@link ConcurrentInitializer} for creating the value
    175     * @return the value stored in the map after this operation; this may or may
    176     * not be the object created by the {@link ConcurrentInitializer}
    177     * @throws ConcurrentRuntimeException if the initializer throws an exception
    178     */
    179    public static <K, V> V createIfAbsentUnchecked(final ConcurrentMap<K, V> map,
    180            final K key, final ConcurrentInitializer<V> init) {
    181        try {
    182            return createIfAbsent(map, key, init);
    183        } catch (final ConcurrentException cex) {
    184            throw new ConcurrentRuntimeException(cex.getCause());
    185        }
    186    }
    187
    188    /**
    189     * Inspects the cause of the specified {@link ExecutionException} and
    190     * creates a {@link ConcurrentException} with the checked cause if
    191     * necessary. This method performs the following checks on the cause of the
    192     * passed in exception:
    193     * <ul>
    194     * <li>If the passed in exception is <strong>null</strong> or the cause is
    195     * <strong>null</strong>, this method returns <strong>null</strong>.</li>
    196     * <li>If the cause is a runtime exception, it is directly thrown.</li>
    197     * <li>If the cause is an error, it is directly thrown, too.</li>
    198     * <li>In any other case the cause is a checked exception. The method then
    199     * creates a {@link ConcurrentException}, initializes it with the cause, and
    200     * returns it.</li>
    201     * </ul>
    202     *
    203     * @param ex the exception to be processed
    204     * @return a {@link ConcurrentException} with the checked cause
    205     */
    206    public static ConcurrentException extractCause(final ExecutionException ex) {
    207        if (ex == null || ex.getCause() == null) {
    208            return null;
    209        }
    210        ExceptionUtils.throwUnchecked(ex.getCause());
    211        return new ConcurrentException(ex.getMessage(), ex.getCause());
    212    }
    213
    214    /**
    215     * Inspects the cause of the specified {@link ExecutionException} and
    216     * creates a {@link ConcurrentRuntimeException} with the checked cause if
    217     * necessary. This method works exactly like
    218     * {@link #extractCause(ExecutionException)}. The only difference is that
    219     * the cause of the specified {@link ExecutionException} is extracted as a
    220     * runtime exception. This is an alternative for client code that does not
    221     * want to deal with checked exceptions.
    222     *
    223     * @param ex the exception to be processed
    224     * @return a {@link ConcurrentRuntimeException} with the checked cause
    225     */
    226    public static ConcurrentRuntimeException extractCauseUnchecked(final ExecutionException ex) {
    227        if (ex == null || ex.getCause() == null) {
    228            return null;
    229        }
    230        ExceptionUtils.throwUnchecked(ex.getCause());
    231        return new ConcurrentRuntimeException(ex.getMessage(), ex.getCause());
    232    }
    233
    234    /**
    235     * Handles the specified {@link ExecutionException}. This method calls
    236     * {@link #extractCause(ExecutionException)} for obtaining the cause of the
    237     * exception - which might already cause an unchecked exception or an error
    238     * being thrown. If the cause is a checked exception however, it is wrapped
    239     * in a {@link ConcurrentException}, which is thrown. If the passed in
    240     * exception is <strong>null</strong> or has no cause, the method simply returns
    241     * without throwing an exception.
    242     *
    243     * @param ex the exception to be handled
    244     * @throws ConcurrentException if the cause of the {@code
    245     * ExecutionException} is a checked exception
    246     */
    247    public static void handleCause(final ExecutionException ex) throws ConcurrentException {
    248        final ConcurrentException cause = extractCause(ex);
    249        if (cause != null) {
    250            throw cause;
    251        }
    252    }
    253
    254    /**
    255     * Handles the specified {@link ExecutionException} and transforms it into a
    256     * runtime exception. This method works exactly like
    257     * {@link #handleCause(ExecutionException)}, but instead of a
    258     * {@link ConcurrentException} it throws a
    259     * {@link ConcurrentRuntimeException}. This is an alternative for client
    260     * code that does not want to deal with checked exceptions.
    261     *
    262     * @param ex the exception to be handled
    263     * @throws ConcurrentRuntimeException if the cause of the {@code
    264     * ExecutionException} is a checked exception; this exception is then
    265     * wrapped in the thrown runtime exception
    266     */
    267    public static void handleCauseUnchecked(final ExecutionException ex) {
    268        final ConcurrentRuntimeException cause = extractCauseUnchecked(ex);
    269        if (cause != null) {
    270            throw cause;
    271        }
    272    }
    273
    274    /**
    275     * Invokes the specified {@link ConcurrentInitializer} and returns the
    276     * object produced by the initializer. This method just invokes the {@code
    277     * get()} method of the given {@link ConcurrentInitializer}. It is
    278     * <strong>null</strong>-safe: if the argument is <strong>null</strong>, result is also
    279     * <strong>null</strong>.
    280     *
    281     * @param <T> the type of the object produced by the initializer
    282     * @param initializer the {@link ConcurrentInitializer} to be invoked
    283     * @return the object managed by the {@link ConcurrentInitializer}
    284     * @throws ConcurrentException if the {@link ConcurrentInitializer} throws
    285     * an exception
    286     */
    287    public static <T> T initialize(final ConcurrentInitializer<T> initializer)
    288            throws ConcurrentException {
    289        return initializer != null ? initializer.get() : null;
    290    }
    291
    292    /**
    293     * Invokes the specified {@link ConcurrentInitializer} and transforms
    294     * occurring exceptions to runtime exceptions. This method works like
    295     * {@link #initialize(ConcurrentInitializer)}, but if the {@code
    296     * ConcurrentInitializer} throws a {@link ConcurrentException}, it is
    297     * caught, and the cause is wrapped in a {@link ConcurrentRuntimeException}.
    298     * So client code does not have to deal with checked exceptions.
    299     *
    300     * @param <T> the type of the object produced by the initializer
    301     * @param initializer the {@link ConcurrentInitializer} to be invoked
    302     * @return the object managed by the {@link ConcurrentInitializer}
    303     * @throws ConcurrentRuntimeException if the initializer throws an exception
    304     */
    305    public static <T> T initializeUnchecked(final ConcurrentInitializer<T> initializer) {
    306        try {
    307            return initialize(initializer);
    308        } catch (final ConcurrentException cex) {
    309            throw new ConcurrentRuntimeException(cex.getCause());
    310        }
    311    }
    312
    313    /**
    314     * Puts a value in the specified {@link ConcurrentMap} if the key is not yet
    315     * present. This method works similar to the {@code putIfAbsent()} method of
    316     * the {@link ConcurrentMap} interface, but the value returned is different.
    317     * Basically, this method is equivalent to the following code fragment:
    318     *
    319     * <pre>
    320     * if (!map.containsKey(key)) {
    321     *     map.put(key, value);
    322     *     return value;
    323     * } else {
    324     *     return map.get(key);
    325     * }
    326     * </pre>
    327     *
    328     * <p>
    329     * except that the action is performed atomically. So this method always
    330     * returns the value which is stored in the map.
    331     * </p>
    332     * <p>
    333     * This method is <strong>null</strong>-safe: It accepts a <strong>null</strong> map as input
    334     * without throwing an exception. In this case the return value is
    335     * <strong>null</strong>, too.
    336     * </p>
    337     *
    338     * @param <K> the type of the keys of the map
    339     * @param <V> the type of the values of the map
    340     * @param map the map to be modified
    341     * @param key the key of the value to be added
    342     * @param value the value to be added
    343     * @return the value stored in the map after this operation
    344     */
    345    public static <K, V> V putIfAbsent(final ConcurrentMap<K, V> map, final K key, final V value) {
    346        if (map == null) {
    347            return null;
    348        }
    349        final V result = map.putIfAbsent(key, value);
    350        return result != null ? result : value;
    351    }
    352
    353    /**
    354     * Private constructor so that no instances can be created. This class
    355     * contains only static utility methods.
    356     */
    357    private ConcurrentUtils() {
    358    }
    359
    360}