src/org/sonews/ShutdownHook.java
author František Kučera <franta-hg@frantovo.cz>
Sat Nov 05 00:06:09 2011 +0100 (2011-11-05)
changeset 115 e5bfc969d41f
parent 37 74139325d305
permissions -rwxr-xr-x
SMTP: correct unescaping of posted messages containing lines with single dot.
     1 /*
     2  *   SONEWS News Server
     3  *   see AUTHORS for the list of contributors
     4  *
     5  *   This program is free software: you can redistribute it and/or modify
     6  *   it under the terms of the GNU General Public License as published by
     7  *   the Free Software Foundation, either version 3 of the License, or
     8  *   (at your option) any later version.
     9  *
    10  *   This program is distributed in the hope that it will be useful,
    11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  *   GNU General Public License for more details.
    14  *
    15  *   You should have received a copy of the GNU General Public License
    16  *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 package org.sonews;
    19 
    20 import java.sql.SQLException;
    21 import java.util.Map;
    22 import org.sonews.daemon.AbstractDaemon;
    23 
    24 /**
    25  * Will force all other threads to shutdown cleanly.
    26  * @author Christian Lins
    27  * @since sonews/0.5.0
    28  */
    29 class ShutdownHook extends Thread {
    30 
    31 	/**
    32 	 * Called when the JVM exits.
    33 	 */
    34 	@Override
    35 	public void run() {
    36 		System.out.println("sonews: Trying to shutdown all threads...");
    37 
    38 		Map<Thread, StackTraceElement[]> threadsMap = Thread.getAllStackTraces();
    39 		for (Thread thread : threadsMap.keySet()) {
    40 			// Interrupt the thread if it's a AbstractDaemon
    41 			AbstractDaemon daemon;
    42 			if (thread instanceof AbstractDaemon && thread.isAlive()) {
    43 				try {
    44 					daemon = (AbstractDaemon) thread;
    45 					daemon.shutdownNow();
    46 				} catch (SQLException ex) {
    47 					System.out.println("sonews: " + ex);
    48 				}
    49 			}
    50 		}
    51 
    52 		for (Thread thread : threadsMap.keySet()) {
    53 			AbstractDaemon daemon;
    54 			if (thread instanceof AbstractDaemon && thread.isAlive()) {
    55 				daemon = (AbstractDaemon) thread;
    56 				System.out.println("sonews: Waiting for " + daemon + " to exit...");
    57 				try {
    58 					daemon.join(500);
    59 				} catch (InterruptedException ex) {
    60 					System.out.println(ex.getLocalizedMessage());
    61 				}
    62 			}
    63 		}
    64 
    65 		// We have notified all not-sleeping AbstractDaemons of the shutdown;
    66 		// all other threads can be simply purged on VM shutdown
    67 
    68 		System.out.println("sonews: Clean shutdown.");
    69 	}
    70 }