    001/*
    002    Licensed to the Apache Software Foundation (ASF) under one
    003    or more contributor license agreements.  See the NOTICE file
    004    distributed with this work for additional information
    005    regarding copyright ownership.  The ASF licenses this file
    006    to you under the Apache License, Version 2.0 (the
    007    "License"); you may not use this file except in compliance
    008    with the License.  You may obtain a copy of the License at
    009
    010       http://www.apache.org/licenses/LICENSE-2.0
    011
    012    Unless required by applicable law or agreed to in writing,
    013    software distributed under the License is distributed on an
    014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    015    KIND, either express or implied.  See the License for the
    016    specific language governing permissions and limitations
    017    under the License.
    018 */
    019package org.apache.wiki;
    020
    021import org.apache.logging.log4j.LogManager;
    022import org.apache.logging.log4j.Logger;
    023import org.apache.wiki.api.core.Engine;
    024import org.apache.wiki.event.WikiEngineEvent;
    025import org.apache.wiki.event.WikiEvent;
    026import org.apache.wiki.event.WikiEventListener;
    027
    028
    029/**
    030 * Abstract Thread subclass that operates in the background; when it detects the {@link WikiEngineEvent#SHUTDOWN} event,
    031 * it terminates itself. Subclasses of this method need only implement the method {@link #backgroundTask()}, instead of
    032 * the normal {@link Thread#run()}, and provide a constructor that passes the Engine and sleep interval. This class is thread-safe.
    033 */
    034public abstract class WikiBackgroundThread extends Thread implements WikiEventListener {
    035
    036    private static final Logger LOG = LogManager.getLogger( WikiBackgroundThread.class );
    037    private volatile boolean m_killMe;
    038    private final Engine m_engine;
    039    private final int m_interval;
    040    private static final long POLLING_INTERVAL = 1_000L;
    041
    042    /**
    043     * Constructs a new instance of this background thread with a specified sleep interval, and adds the new instance
    044     * to the wiki engine's event listeners.
    045     *
    046     * @param engine the wiki engine
    047     * @param sleepInterval the interval between invocations of
    048     * the thread's {@link Thread#run()} method, in seconds
    049     */
    050    public WikiBackgroundThread( final Engine engine, final int sleepInterval ) {
    051        super();
    052        m_engine = engine;
    053        m_interval = sleepInterval;
    054        engine.addWikiEventListener( this );
    055        setDaemon( false );
    056    }
    057
    058    /**
    059     * Listens for {@link org.apache.wiki.event.WikiEngineEvent#SHUTDOWN} and, if detected, marks the thread for death.
    060     *
    061     * @param event {@inheritDoc}
    062     * @see org.apache.wiki.event.WikiEventListener#actionPerformed(org.apache.wiki.event.WikiEvent)
    063     */
    064    @Override
    065    public final void actionPerformed( final WikiEvent event ) {
    066        if ( event instanceof WikiEngineEvent ) {
    067            if ( event.getType() == WikiEngineEvent.SHUTDOWN ) {
    068                LOG.warn( "Detected wiki engine shutdown: killing " + getName() + "." );
    069                m_killMe = true;
    070            }
    071        }
    072    }
    073
    074    /**
    075     * Abstract method that performs the actual work for this background thread; subclasses must implement this method.
    076     *
    077     * @throws Exception Any exception can be thrown
    078     */
    079    public abstract void backgroundTask() throws Exception;
    080
    081    /**
    082     * Returns the Engine that created this background thread.
    083     *
    084     * @return the wiki engine
    085     */
    086    public Engine getEngine() {
    087        return m_engine;
    088    }
    089
    090    /**
    091     *  Requests the shutdown of this background thread.  Note that the shutdown is not immediate.
    092     *
    093     *  @since 2.4.92
    094     */
    095    public void shutdown() {
    096        m_killMe = true;
    097    }
    098
    099    /**
    100     * Runs the background thread's {@link #backgroundTask()} method at the interval specified at construction.
    101     * The thread will initially pause for a full sleep interval before starting, after which it will execute
    102     * {@link #startupTask()}. This method will cleanly terminate the thread if it has previously been marked as
    103     * dead, before which it will execute {@link #shutdownTask()}. If any of the three methods return an exception,
    104     * it will be re-thrown as a {@link org.apache.wiki.InternalWikiException}.
    105     *
    106     * @see java.lang.Thread#run()
    107     */
    108    @Override
    109    public final void run() {
    110        try {
    111            // Perform the initial startup task
    112            final String name = getName();
    113            LOG.warn( "Starting up background thread: " + name + ".");
    114            startupTask();
    115
    116            // Perform the background task; check every second for thread death
    117            while( !m_killMe ) {
    118                // Perform the background task
    119                // LOG.debug( "Running background task: " + name + "." );
    120                backgroundTask();
    121
    122                // Sleep for the interval we're supposed to, but wake up every POLLING_INTERVAL to see if thread should die
    123                boolean interrupted = false;
    124                try {
    125                    for( int i = 0; i < m_interval; i++ ) {
    126                        Thread.sleep( POLLING_INTERVAL );
    127                        if( m_killMe ) {
    128                            interrupted = true;
    129                            LOG.warn( "Interrupted background thread: " + name + "." );
    130                            break;
    131                        }
    132                    }
    133                    if( interrupted ) {
    134                        break;
    135                    }
    136                } catch( final Throwable t ) {
    137                    LOG.error( "Background thread error: (stack trace follows)", t );
    138                }
    139            }
    140
    141            // Perform the shutdown task
    142            shutdownTask();
    143        } catch( final Throwable t ) {
    144            LOG.error( "Background thread error: (stack trace follows)", t );
    145            throw new InternalWikiException( t.getMessage() ,t );
    146        }
    147    }
    148
    149    /**
    150     * Executes a task after shutdown signal was detected. By default, this method does nothing; override it
    151     * to implement custom functionality.
    152     *
    153     * @throws Exception Any exception can be thrown.
    154     */
    155    public void shutdownTask() throws Exception {
    156    }
    157
    158    /**
    159     * Executes a task just after the thread's {@link Thread#run()} method starts, but before the {@link #backgroundTask()} task executes.
    160     * By default, this method does nothing; override it to implement custom functionality.
    161     *
    162     * @throws Exception Any exception can be thrown.
    163     */
    164    public void startupTask() throws Exception {
    165    }
    166
    167}