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 */
019 package org.apache.wiki;
020
021 import org.apache.log4j.Logger;
022 import org.apache.wiki.event.WikiEngineEvent;
023 import org.apache.wiki.event.WikiEvent;
024 import org.apache.wiki.event.WikiEventListener;
025
026
027 /**
028 * Abstract Thread subclass that operates in the background; when it detects the {@link WikiEngineEvent#SHUTDOWN} event,
029 * it terminates itself. Subclasses of this method need only implement the method {@link #backgroundTask()}, instead of
030 * the normal {@link Thread#run()}, and provide a constructor that passes the WikiEngine and sleep interval. This
031 * class is thread-safe.
032 */
033 public abstract class WikiBackgroundThread extends Thread implements WikiEventListener {
034
035 private static final Logger LOG = Logger.getLogger(WikiBackgroundThread.class);
036 private volatile boolean m_killMe = false;
037 private final WikiEngine m_engine;
038 private final int m_interval;
039 private static final long POLLING_INTERVAL = 1000L;
040
041 /**
042 * Constructs a new instance of this background thread with a specified sleep interval, and adds the new instance
043 * to the wiki engine's event listeners.
044 *
045 * @param engine the wiki engine
046 * @param sleepInterval the interval between invocations of
047 * the thread's {@link Thread#run()} method, in seconds
048 */
049 public WikiBackgroundThread( WikiEngine engine, int sleepInterval ) {
050 super();
051 m_engine = engine;
052 m_interval = sleepInterval;
053 engine.addWikiEventListener( this );
054 setDaemon( false );
055 }
056
057 /**
058 * Listens for {@link org.apache.wiki.event.WikiEngineEvent#SHUTDOWN} and, if detected, marks the thread for death.
059 *
060 * @param event {@inheritDoc}
061 * @see org.apache.wiki.event.WikiEventListener#actionPerformed(org.apache.wiki.event.WikiEvent)
062 */
063 public final void actionPerformed( WikiEvent event ) {
064 if ( event instanceof WikiEngineEvent ) {
065 if ( ((WikiEngineEvent)event).getType() == WikiEngineEvent.SHUTDOWN ) {
066 LOG.warn( "Detected wiki engine shutdown: killing " + getName() + "." );
067 m_killMe = true;
068 }
069 }
070 }
071
072 /**
073 * Abstract method that performs the actual work for this background thread; subclasses must implement this method.
074 *
075 * @throws Exception Any exception can be thrown
076 */
077 public abstract void backgroundTask() throws Exception;
078
079 /**
080 * Returns the WikiEngine that created this background thread.
081 *
082 * @return the wiki engine
083 */
084 public WikiEngine getEngine() {
085 return m_engine;
086 }
087
088 /**
089 * Requests the shutdown of this background thread. Note that the shutdown is not immediate.
090 *
091 * @since 2.4.92
092 */
093 public void shutdown() {
094 m_killMe = true;
095 }
096
097 /**
098 * Runs the background thread's {@link #backgroundTask()} method at the interval specified at construction.
099 * The thread will initially pause for a full sleep interval before starting, after which it will execute
100 * {@link #startupTask()}. This method will cleanly terminate the thread if it has previously been marked as
101 * dead, before which it will execute {@link #shutdownTask()}. If any of the three methods return an exception,
102 * it will be re-thrown as a {@link org.apache.wiki.InternalWikiException}.
103 *
104 * @see java.lang.Thread#run()
105 */
106 public final void run() {
107 try {
108 // Perform the initial startup task
109 final String name = getName();
110 LOG.warn( "Starting up background thread: " + name + ".");
111 startupTask();
112
113 // Perform the background task; check every
114 // second for thread death
115 while( !m_killMe ) {
116 // Perform the background task
117 // log.debug( "Running background task: " + name + "." );
118 backgroundTask();
119
120 // Sleep for the interval we're supposed to, but
121 // wake up every POLLING_INTERVAL to see if thread should die
122 boolean interrupted = false;
123 try {
124 for( int i = 0; i < m_interval; i++ ) {
125 Thread.sleep( POLLING_INTERVAL );
126 if( m_killMe ) {
127 interrupted = true;
128 LOG.warn( "Interrupted background thread: " + name + "." );
129 break;
130 }
131 }
132 if( interrupted ) {
133 break;
134 }
135 } catch( Throwable t ) {
136 LOG.error( "Background thread error: (stack trace follows)", t );
137 }
138 }
139
140 // Perform the shutdown task
141 shutdownTask();
142 } catch( Throwable t ) {
143 LOG.error( "Background thread error: (stack trace follows)", t );
144 throw new InternalWikiException( t.getMessage() );
145 }
146 }
147
148 /**
149 * Executes a task after shutdown signal was detected. By default, this method does nothing; override it
150 * to implement custom functionality.
151 *
152 * @throws Exception Any exception can be thrown.
153 */
154 public void shutdownTask() throws Exception {
155 }
156
157 /**
158 * Executes a task just after the thread's {@link Thread#run()} method starts, but before the
159 * {@link #backgroundTask()} task executes. By default, this method does nothing; override it to implement
160 * custom functionality.
161 *
162 * @throws Exception Any exception can be thrown.
163 */
164 public void startupTask() throws Exception {
165 }
166
167 }