001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software GmbH, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 * 
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 * 
027 * 
028 * This library is based to some extend on code from the 
029 * OpenSymphony Quartz project. Original copyright notice:
030 * 
031 * Copyright James House (c) 2001-2005
032 * 
033 * All rights reserved.
034 * 
035 * Redistribution and use in source and binary forms, with or without
036 * modification, are permitted provided that the following conditions are met: 1.
037 * Redistributions of source code must retain the above copyright notice, this
038 * list of conditions and the following disclaimer. 2. Redistributions in
039 * binary form must reproduce the above copyright notice, this list of
040 * conditions and the following disclaimer in the documentation and/or other
041 * materials provided with the distribution.
042 * 
043 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
044 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
045 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
046 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
047 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
048 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
049 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
050 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
051 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
052 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
053 */
054
055package org.opencms.scheduler;
056
057import org.opencms.main.CmsLog;
058
059import org.apache.commons.logging.Log;
060
061import org.quartz.SchedulerConfigException;
062import org.quartz.spi.ThreadPool;
063
064/**
065 * Simple thread pool used for the Quartz scheduler in OpenCms.<p>
066 * 
067 * @since 6.0.0 
068 */
069public class CmsSchedulerThreadPool implements ThreadPool {
070
071    /** The log object for this class. */
072    private static final Log LOG = CmsLog.getLog(CmsSchedulerThreadPool.class);
073
074    /** The current thread count. */
075    private int m_currentThreadCount;
076
077    /** The inheri group. */
078    private boolean m_inheritGroup;
079
080    /** The inherit loader. */
081    private boolean m_inheritLoader;
082
083    /** The initial thread count. */
084    private int m_initialThreadCount;
085
086    /** Flag indicating if the system is shutting down. */
087    private boolean m_isShutdown;
088
089    /** Flag indicating whether to create thread deamons. */
090    private boolean m_makeThreadsDaemons;
091
092    /** The max thread count. */
093    private int m_maxThreadCount;
094
095    /** The next runnable. */
096    private Runnable m_nextRunnable;
097
098    /** The next runnable lock. */
099    private Object m_nextRunnableLock;
100
101    /** The thread group. */
102    private ThreadGroup m_threadGroup;
103
104    /** The thread name prefix. */
105    private String m_threadNamePrefix;
106
107    /** The thread priority. */
108    private int m_threadPriority;
109
110    /** The threads. */
111    private CmsSchedulerThread[] m_workers;
112
113    /**
114     * Create a new <code>CmsSchedulerThreadPool</code> with default values.
115     * 
116     * This will create a pool with 0 initial and 10 maximum threads running 
117     * in normal priority.<p>
118     * 
119     * @see #CmsSchedulerThreadPool(int, int, int)
120     */
121    public CmsSchedulerThreadPool() {
122
123        this(0, 10, Thread.NORM_PRIORITY);
124    }
125
126    /**
127     * Create a new <code>CmsSchedulerThreadPool</code> with the specified number
128     * of threads that have the given priority.
129     * 
130     * The OpenCms scheduler thread pool will initially start with provided number of
131     * active scheduler threads.
132     * When a thread is requested by the scheduler, and no "free" threads are available,
133     * a new thread will be added to the pool and used for execution. The pool 
134     * will be allowed to grow until it has reached the configured number 
135     * of maximum threads.<p>
136     * 
137     * @param initialThreadCount the initial number of threads for the pool
138     * @param maxThreadCount maximum number of threads the pool is allowed to grow
139     * @param threadPriority the thread priority for the scheduler threads
140     * 
141     * @see java.lang.Thread
142     */
143    public CmsSchedulerThreadPool(int initialThreadCount, int maxThreadCount, int threadPriority) {
144
145        m_inheritGroup = true;
146        m_inheritLoader = true;
147        m_nextRunnableLock = new Object();
148        m_threadNamePrefix = "OpenCms: Scheduler Thread ";
149        m_makeThreadsDaemons = true;
150        m_initialThreadCount = initialThreadCount;
151        m_currentThreadCount = 0;
152        m_maxThreadCount = maxThreadCount;
153        m_threadPriority = threadPriority;
154    }
155
156    /**
157     * @see org.quartz.spi.ThreadPool
158     * 
159     * @return if the pool should be blocked for available threads
160     */
161    public int blockForAvailableThreads() {
162
163        // Waiting will be done in runInThread so we always return 1
164        return 1;
165    }
166
167    /**
168     * @see org.quartz.spi.ThreadPool#getPoolSize()
169     */
170    public int getPoolSize() {
171
172        return m_currentThreadCount;
173    }
174
175    /**
176     * Returns the thread priority of the threads in the scheduler pool.<p>
177     * 
178     * @return the thread priority of the threads in the scheduler pool 
179     */
180    public int getThreadPriority() {
181
182        return m_threadPriority;
183    }
184
185    /**
186     * @see org.quartz.spi.ThreadPool#initialize()
187     */
188    public void initialize() throws SchedulerConfigException {
189
190        if ((m_maxThreadCount <= 0) || (m_maxThreadCount > 200)) {
191            throw new SchedulerConfigException(Messages.get().getBundle().key(Messages.ERR_MAX_THREAD_COUNT_BOUNDS_0));
192        }
193        if ((m_initialThreadCount < 0) || (m_initialThreadCount > m_maxThreadCount)) {
194            throw new SchedulerConfigException(Messages.get().getBundle().key(Messages.ERR_INIT_THREAD_COUNT_BOUNDS_0));
195        }
196        if ((m_threadPriority <= 0) || (m_threadPriority > 9)) {
197            throw new SchedulerConfigException(Messages.get().getBundle().key(Messages.ERR_SCHEDULER_PRIORITY_BOUNDS_0));
198        }
199
200        if (m_inheritGroup) {
201            m_threadGroup = Thread.currentThread().getThreadGroup();
202        } else {
203            // follow the threadGroup tree to the root thread group
204            m_threadGroup = Thread.currentThread().getThreadGroup();
205            ThreadGroup parent = m_threadGroup;
206            while (!parent.getName().equals("main")) {
207                m_threadGroup = parent;
208                parent = m_threadGroup.getParent();
209            }
210            m_threadGroup = new ThreadGroup(parent, this.getClass().getName());
211        }
212
213        if (m_inheritLoader) {
214            LOG.debug(Messages.get().getBundle().key(
215                Messages.LOG_USING_THREAD_CLASSLOADER_1,
216                Thread.currentThread().getName()));
217        }
218
219        // create the worker threads and start them
220        m_workers = new CmsSchedulerThread[m_maxThreadCount];
221        for (int i = 0; i < m_initialThreadCount; ++i) {
222            growThreadPool();
223        }
224    }
225
226    /**
227     * Run the given <code>Runnable</code> object in the next available
228     * <code>Thread</code>.<p>
229     * 
230     * If while waiting the thread pool is asked to
231     * shut down, the Runnable is executed immediately within a new additional
232     * thread.<p>
233     * 
234     * @param runnable the <code>Runnable</code> to run
235     * @return true if the <code>Runnable</code> was run
236     */
237    public boolean runInThread(Runnable runnable) {
238
239        if (runnable == null) {
240            return false;
241        }
242
243        if (m_isShutdown) {
244            LOG.debug(Messages.get().getBundle().key(Messages.LOG_THREAD_POOL_UNAVAILABLE_0));
245            return false;
246        }
247
248        boolean hasNextRunnable;
249        synchronized (m_nextRunnableLock) {
250            // must synchronize here to avoid potential double checked locking
251            hasNextRunnable = (m_nextRunnable != null);
252        }
253
254        if (hasNextRunnable || (m_currentThreadCount == 0)) {
255            // try to grow the thread pool since other runnables are already waiting
256            growThreadPool();
257        }
258
259        synchronized (m_nextRunnableLock) {
260
261            // wait until a worker thread has taken the previous Runnable
262            // or until the thread pool is asked to shutdown
263            while ((m_nextRunnable != null) && !m_isShutdown) {
264                try {
265                    m_nextRunnableLock.wait(1000);
266                } catch (InterruptedException e) {
267                    // can be ignores
268                }
269            }
270
271            // during normal operation, not shutdown, set the nextRunnable
272            // and notify the worker threads waiting (getNextRunnable())
273            if (!m_isShutdown) {
274                m_nextRunnable = runnable;
275                m_nextRunnableLock.notifyAll();
276            }
277        }
278
279        // if the thread pool is going down, execute the Runnable
280        // within a new additional worker thread (no thread from the pool)
281        // note: the synchronized section should be as short (time) as
282        // possible as starting a new thread is not a quick action
283        if (m_isShutdown) {
284            CmsSchedulerThread thread = new CmsSchedulerThread(
285                this,
286                m_threadGroup,
287                m_threadNamePrefix + "(final)",
288                m_threadPriority,
289                false,
290                runnable);
291            thread.start();
292        }
293
294        return true;
295    }
296
297    /**
298     * Terminate any worker threads in this thread group.<p>
299     * 
300     * Jobs currently in progress will be allowed to complete.<p>
301     */
302    public void shutdown() {
303
304        shutdown(true);
305    }
306
307    /**
308     * Terminate all threads in this thread group.<p>
309     * 
310     * @param waitForJobsToComplete if true,, all current jobs will be allowed to complete
311     */
312    public void shutdown(boolean waitForJobsToComplete) {
313
314        m_isShutdown = true;
315
316        // signal each scheduler thread to shut down
317        for (int i = 0; i < m_currentThreadCount; i++) {
318            if (m_workers[i] != null) {
319                m_workers[i].shutdown();
320            }
321        }
322
323        // give waiting (wait(1000)) worker threads a chance to shut down
324        // active worker threads will shut down after finishing their
325        // current job
326        synchronized (m_nextRunnableLock) {
327            m_nextRunnableLock.notifyAll();
328        }
329
330        if (waitForJobsToComplete) {
331            // wait until all worker threads are shut down
332            int alive = m_currentThreadCount;
333            while (alive > 0) {
334                alive = 0;
335                for (int i = 0; i < m_currentThreadCount; i++) {
336                    if (m_workers[i].isAlive()) {
337                        try {
338                            if (LOG.isDebugEnabled()) {
339                                LOG.debug(Messages.get().getBundle().key(
340                                    Messages.LOG_THREAD_POOL_WAITING_1,
341                                    new Integer(i)));
342                            }
343
344                            // note: with waiting infinite - join(0) - the application 
345                            // may appear to 'hang' 
346                            // waiting for a finite time however requires an additional loop (alive)
347                            alive++;
348                            m_workers[i].join(200);
349                        } catch (InterruptedException e) {
350                            // can be ignored
351                        }
352                    }
353                }
354            }
355
356            int activeCount = m_threadGroup.activeCount();
357            if ((activeCount > 0) && LOG.isInfoEnabled()) {
358                LOG.info(Messages.get().getBundle().key(
359                    Messages.LOG_THREAD_POOL_STILL_ACTIVE_1,
360                    new Integer(activeCount)));
361            }
362            if (LOG.isDebugEnabled()) {
363                LOG.debug(Messages.get().getBundle().key(Messages.LOG_THREAD_POOL_SHUTDOWN_0));
364            }
365        }
366    }
367
368    /**
369     * Dequeue the next pending <code>Runnable</code>.<p>
370     * 
371     * @return the next pending <code>Runnable</code>
372     * @throws InterruptedException if something goes wrong
373     */
374    protected Runnable getNextRunnable() throws InterruptedException {
375
376        Runnable toRun = null;
377
378        // Wait for new Runnable (see runInThread()) and notify runInThread()
379        // in case the next Runnable is already waiting.
380        synchronized (m_nextRunnableLock) {
381            if (m_nextRunnable == null) {
382                m_nextRunnableLock.wait(1000);
383            }
384
385            if (m_nextRunnable != null) {
386                toRun = m_nextRunnable;
387                m_nextRunnable = null;
388                m_nextRunnableLock.notifyAll();
389            }
390        }
391
392        return toRun;
393    }
394
395    /**
396     * Grows the thread pool by one new thread if the maximum pool size 
397     * has not been reached.<p>
398     */
399    private void growThreadPool() {
400
401        if (m_currentThreadCount < m_maxThreadCount) {
402            // if maximum number is not reached grow the thread pool
403            synchronized (m_nextRunnableLock) {
404                m_workers[m_currentThreadCount] = new CmsSchedulerThread(this, m_threadGroup, m_threadNamePrefix
405                    + m_currentThreadCount, m_threadPriority, m_makeThreadsDaemons);
406                m_workers[m_currentThreadCount].start();
407                if (m_inheritLoader) {
408                    m_workers[m_currentThreadCount].setContextClassLoader(Thread.currentThread().getContextClassLoader());
409                }
410                // increas the current size
411                m_currentThreadCount++;
412                // notify the waiting threads
413                m_nextRunnableLock.notifyAll();
414            }
415        }
416    }
417}