    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.configuration2.reloading;
    018
    019import java.util.concurrent.Executors;
    020import java.util.concurrent.ScheduledExecutorService;
    021import java.util.concurrent.ScheduledFuture;
    022import java.util.concurrent.ThreadFactory;
    023import java.util.concurrent.TimeUnit;
    024
    025import org.apache.commons.lang3.concurrent.BasicThreadFactory;
    026
    027/**
    028 * <p>
    029 * A timer-based trigger for reloading checks.
    030 * </p>
    031 * <p>
    032 * An instance of this class is constructed with a reference to a {@link ReloadingController} and a period. After
    033 * calling the {@code start()} method a periodic task is started which calls
    034 * {@link ReloadingController#checkForReloading(Object)} on the associated reloading controller. This way changes on a
    035 * configuration source can be detected without client code having to poll actively. The {@code ReloadingController}
    036 * will perform its checks and generates events if it detects the need for a reloading operation.
    037 * </p>
    038 * <p>
    039 * Triggering of the controller can be disabled by calling the {@code stop()} method and later be resumed by calling
    040 * {@code start()} again. When the trigger is no more needed its {@code shutdown()} method should be called.
    041 * </p>
    042 * <p>
    043 * When creating an instance a {@code ScheduledExecutorService} can be provided which is then used by the object.
    044 * Otherwise, a default executor service is created and used. When shutting down this object it can be specified whether
    045 * the {@code ScheduledExecutorService} should be shut down, too.
    046 * </p>
    047 *
    048 * @since 2.0
    049 * @see ReloadingController
    050 */
    051public class PeriodicReloadingTrigger {
    052    /** The executor service used by this trigger. */
    053    private final ScheduledExecutorService executorService;
    054
    055    /** The associated reloading controller. */
    056    private final ReloadingController controller;
    057
    058    /** The parameter to be passed to the controller. */
    059    private final Object controllerParam;
    060
    061    /** The period. */
    062    private final long period;
    063
    064    /** The time unit. */
    065    private final TimeUnit timeUnit;
    066
    067    /** Stores the future object for the current trigger task. */
    068    private ScheduledFuture<?> triggerTask;
    069
    070    /**
    071     * Creates a new instance of {@code PeriodicReloadingTrigger} and sets all parameters.
    072     *
    073     * @param ctrl the {@code ReloadingController} (must not be <b>null</b>)
    074     * @param ctrlParam the optional parameter to be passed to the controller when doing reloading checks
    075     * @param triggerPeriod the period in which the controller is triggered
    076     * @param unit the time unit for the period
    077     * @param exec the executor service to use (can be <b>null</b>, then a default executor service is created
    078     * @throws IllegalArgumentException if a required argument is missing
    079     */
    080    public PeriodicReloadingTrigger(final ReloadingController ctrl, final Object ctrlParam, final long triggerPeriod, final TimeUnit unit,
    081        final ScheduledExecutorService exec) {
    082        if (ctrl == null) {
    083            throw new IllegalArgumentException("ReloadingController must not be null!");
    084        }
    085
    086        controller = ctrl;
    087        controllerParam = ctrlParam;
    088        period = triggerPeriod;
    089        timeUnit = unit;
    090        executorService = exec != null ? exec : createDefaultExecutorService();
    091    }
    092
    093    /**
    094     * Creates a new instance of {@code PeriodicReloadingTrigger} with a default executor service.
    095     *
    096     * @param ctrl the {@code ReloadingController} (must not be <b>null</b>)
    097     * @param ctrlParam the optional parameter to be passed to the controller when doing reloading checks
    098     * @param triggerPeriod the period in which the controller is triggered
    099     * @param unit the time unit for the period
    100     * @throws IllegalArgumentException if a required argument is missing
    101     */
    102    public PeriodicReloadingTrigger(final ReloadingController ctrl, final Object ctrlParam, final long triggerPeriod, final TimeUnit unit) {
    103        this(ctrl, ctrlParam, triggerPeriod, unit, null);
    104    }
    105
    106    /**
    107     * Starts this trigger. The associated {@code ReloadingController} will be triggered according to the specified period.
    108     * The first triggering happens after a period. If this trigger is already started, this invocation has no effect.
    109     */
    110    public synchronized void start() {
    111        if (!isRunning()) {
    112            triggerTask = getExecutorService().scheduleAtFixedRate(createTriggerTaskCommand(), period, period, timeUnit);
    113        }
    114    }
    115
    116    /**
    117     * Stops this trigger. The associated {@code ReloadingController} is no more triggered. If this trigger is already
    118     * stopped, this invocation has no effect.
    119     */
    120    public synchronized void stop() {
    121        if (isRunning()) {
    122            triggerTask.cancel(false);
    123            triggerTask = null;
    124        }
    125    }
    126
    127    /**
    128     * Returns a flag whether this trigger is currently active.
    129     *
    130     * @return a flag whether this trigger is running
    131     */
    132    public synchronized boolean isRunning() {
    133        return triggerTask != null;
    134    }
    135
    136    /**
    137     * Shuts down this trigger and optionally shuts down the {@code ScheduledExecutorService} used by this object. This
    138     * method should be called if this trigger is no more needed. It ensures that the trigger is stopped. If the parameter
    139     * is <b>true</b>, the executor service is also shut down. This should be done if this trigger is the only user of this
    140     * executor service.
    141     *
    142     * @param shutdownExecutor a flag whether the associated {@code ScheduledExecutorService} is to be shut down
    143     */
    144    public void shutdown(final boolean shutdownExecutor) {
    145        stop();
    146        if (shutdownExecutor) {
    147            getExecutorService().shutdown();
    148        }
    149    }
    150
    151    /**
    152     * Shuts down this trigger and its {@code ScheduledExecutorService}. This is a shortcut for {@code shutdown(true)}.
    153     *
    154     * @see #shutdown(boolean)
    155     */
    156    public void shutdown() {
    157        shutdown(true);
    158    }
    159
    160    /**
    161     * Gets the {@code ScheduledExecutorService} used by this object.
    162     *
    163     * @return the associated {@code ScheduledExecutorService}
    164     */
    165    ScheduledExecutorService getExecutorService() {
    166        return executorService;
    167    }
    168
    169    /**
    170     * Creates the task which triggers the reloading controller.
    171     *
    172     * @return the newly created trigger task
    173     */
    174    private Runnable createTriggerTaskCommand() {
    175        return () -> controller.checkForReloading(controllerParam);
    176    }
    177
    178    /**
    179     * Creates a default executor service. This method is called if no executor has been passed to the constructor.
    180     *
    181     * @return the default executor service
    182     */
    183    private static ScheduledExecutorService createDefaultExecutorService() {
    184        final ThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("ReloadingTrigger-%s").daemon(true).build();
    185        return Executors.newScheduledThreadPool(1, factory);
    186    }
    187}