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(
198                Messages.get().getBundle().key(Messages.ERR_SCHEDULER_PRIORITY_BOUNDS_0));
199        }
200
201        if (m_inheritGroup) {
202            m_threadGroup = Thread.currentThread().getThreadGroup();
203        } else {
204            // follow the threadGroup tree to the root thread group
205            m_threadGroup = Thread.currentThread().getThreadGroup();
206            ThreadGroup parent = m_threadGroup;
207            while (!parent.getName().equals("main")) {
208                m_threadGroup = parent;
209                parent = m_threadGroup.getParent();
210            }
211            m_threadGroup = new ThreadGroup(parent, this.getClass().getName());
212        }
213
214        if (m_inheritLoader) {
215            LOG.debug(
216                Messages.get().getBundle().key(
217                    Messages.LOG_USING_THREAD_CLASSLOADER_1,
218                    Thread.currentThread().getName()));
219        }
220
221        // create the worker threads and start them
222        m_workers = new CmsSchedulerThread[m_maxThreadCount];
223        for (int i = 0; i < m_initialThreadCount; ++i) {
224            growThreadPool();
225        }
226    }
227
228    /**
229     * Run the given <code>Runnable</code> object in the next available
230     * <code>Thread</code>.<p>
231     *
232     * If while waiting the thread pool is asked to
233     * shut down, the Runnable is executed immediately within a new additional
234     * thread.<p>
235     *
236     * @param runnable the <code>Runnable</code> to run
237     * @return true if the <code>Runnable</code> was run
238     */
239    public boolean runInThread(Runnable runnable) {
240
241        if (runnable == null) {
242            return false;
243        }
244
245        if (m_isShutdown) {
246            LOG.debug(Messages.get().getBundle().key(Messages.LOG_THREAD_POOL_UNAVAILABLE_0));
247            return false;
248        }
249
250        boolean hasNextRunnable;
251        synchronized (m_nextRunnableLock) {
252            // must synchronize here to avoid potential double checked locking
253            hasNextRunnable = (m_nextRunnable != null);
254        }
255
256        if (hasNextRunnable || (m_currentThreadCount == 0)) {
257            // try to grow the thread pool since other runnables are already waiting
258            growThreadPool();
259        }
260
261        synchronized (m_nextRunnableLock) {
262
263            // wait until a worker thread has taken the previous Runnable
264            // or until the thread pool is asked to shutdown
265            while ((m_nextRunnable != null) && !m_isShutdown) {
266                try {
267                    m_nextRunnableLock.wait(1000);
268                } catch (InterruptedException e) {
269                    // can be ignores
270                }
271            }
272
273            // during normal operation, not shutdown, set the nextRunnable
274            // and notify the worker threads waiting (getNextRunnable())
275            if (!m_isShutdown) {
276                m_nextRunnable = runnable;
277                m_nextRunnableLock.notifyAll();
278            }
279        }
280
281        // if the thread pool is going down, execute the Runnable
282        // within a new additional worker thread (no thread from the pool)
283        // note: the synchronized section should be as short (time) as
284        // possible as starting a new thread is not a quick action
285        if (m_isShutdown) {
286            CmsSchedulerThread thread = new CmsSchedulerThread(
287                this,
288                m_threadGroup,
289                m_threadNamePrefix + "(final)",
290                m_threadPriority,
291                false,
292                runnable);
293            thread.start();
294        }
295
296        return true;
297    }
298
299    /**
300     * Terminate any worker threads in this thread group.<p>
301     *
302     * Jobs currently in progress will be allowed to complete.<p>
303     */
304    public void shutdown() {
305
306        shutdown(true);
307    }
308
309    /**
310     * Terminate all threads in this thread group.<p>
311     *
312     * @param waitForJobsToComplete if true,, all current jobs will be allowed to complete
313     */
314    public void shutdown(boolean waitForJobsToComplete) {
315
316        m_isShutdown = true;
317
318        // signal each scheduler thread to shut down
319        for (int i = 0; i < m_currentThreadCount; i++) {
320            if (m_workers[i] != null) {
321                m_workers[i].shutdown();
322            }
323        }
324
325        // give waiting (wait(1000)) worker threads a chance to shut down
326        // active worker threads will shut down after finishing their
327        // current job
328        synchronized (m_nextRunnableLock) {
329            m_nextRunnableLock.notifyAll();
330        }
331
332        if (waitForJobsToComplete) {
333            // wait until all worker threads are shut down
334            int alive = m_currentThreadCount;
335            while (alive > 0) {
336                alive = 0;
337                for (int i = 0; i < m_currentThreadCount; i++) {
338                    if (m_workers[i].isAlive()) {
339                        try {
340                            if (LOG.isDebugEnabled()) {
341                                LOG.debug(
342                                    Messages.get().getBundle().key(Messages.LOG_THREAD_POOL_WAITING_1, new Integer(i)));
343                            }
344
345                            // note: with waiting infinite - join(0) - the application
346                            // may appear to 'hang'
347                            // waiting for a finite time however requires an additional loop (alive)
348                            alive++;
349                            m_workers[i].join(200);
350                        } catch (InterruptedException e) {
351                            // can be ignored
352                        }
353                    }
354                }
355            }
356
357            int activeCount = m_threadGroup.activeCount();
358            if ((activeCount > 0) && LOG.isInfoEnabled()) {
359                LOG.info(
360                    Messages.get().getBundle().key(Messages.LOG_THREAD_POOL_STILL_ACTIVE_1, 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(
405                    this,
406                    m_threadGroup,
407                    m_threadNamePrefix + m_currentThreadCount,
408                    m_threadPriority,
409                    m_makeThreadsDaemons);
410                m_workers[m_currentThreadCount].start();
411                if (m_inheritLoader) {
412                    m_workers[m_currentThreadCount].setContextClassLoader(
413                        Thread.currentThread().getContextClassLoader());
414                }
415                // increas the current size
416                m_currentThreadCount++;
417                // notify the waiting threads
418                m_nextRunnableLock.notifyAll();
419            }
420        }
421    }
422}