src/org/sonews/ShutdownHook.java
author cli
Wed, 04 May 2011 18:06:24 +0200
changeset 40 f8894df2d079
parent 37 74139325d305
child 49 8df94bfd3e2f
permissions -rwxr-xr-x
Refactoring.
     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 
    19 package org.sonews;
    20 
    21 import java.sql.SQLException;
    22 import java.util.Map;
    23 import org.sonews.daemon.AbstractDaemon;
    24 
    25 /**
    26  * Will force all other threads to shutdown cleanly.
    27  * @author Christian Lins
    28  * @since sonews/0.5.0
    29  */
    30 class ShutdownHook extends Thread
    31 {
    32 
    33 	/**
    34 	 * Called when the JVM exits.
    35 	 */
    36 	@Override
    37 	public void run()
    38 	{
    39 		System.out.println("sonews: Trying to shutdown all threads...");
    40 
    41 		Map<Thread, StackTraceElement[]> threadsMap = Thread.getAllStackTraces();
    42 		for (Thread thread : threadsMap.keySet()) {
    43 			// Interrupt the thread if it's a AbstractDaemon
    44 			AbstractDaemon daemon;
    45 			if (thread instanceof AbstractDaemon && thread.isAlive()) {
    46 				try {
    47 					daemon = (AbstractDaemon) thread;
    48 					daemon.shutdownNow();
    49 				} catch (SQLException ex) {
    50 					System.out.println("sonews: " + ex);
    51 				}
    52 			}
    53 		}
    54 
    55 		for (Thread thread : threadsMap.keySet()) {
    56 			AbstractDaemon daemon;
    57 			if (thread instanceof AbstractDaemon && thread.isAlive()) {
    58 				daemon = (AbstractDaemon) thread;
    59 				System.out.println("sonews: Waiting for " + daemon + " to exit...");
    60 				try {
    61 					daemon.join(500);
    62 				} catch (InterruptedException ex) {
    63 					System.out.println(ex.getLocalizedMessage());
    64 				}
    65 			}
    66 		}
    67 
    68 		// We have notified all not-sleeping AbstractDaemons of the shutdown;
    69 		// all other threads can be simply purged on VM shutdown
    70 
    71 		System.out.println("sonews: Clean shutdown.");
    72 	}
    73 }