public static void safeExit(int status) {
    // Get the list of all threads
    Thread myThrd = Thread.currentThread();
    ThreadGroup thisGroup = myThrd.getThreadGroup();
    int daemons;	// number of daemons threads seen for iteration

    do {
	daemons = 0;
	int count = thisGroup.activeCount();
	Thread[] thrds = new Thread[count + 20]; // +20 for slop
	thisGroup.enumerate(thrds);

	// stop all threads
	for (int i = 0; i < thrds.length; i++) {
	    if (thrds[i] != null && thrds[i] != myThrd) {
		if (thrds[i].isDaemon())
		    daemons++;		// count daemon threads
		else
		    thrds[i].stop();	// stop non-daemon threads
	    }
	}

	// wait for stopped threads to complete
	for (int i = 0; i < thrds.length; i++) {
	    if (thrds[i] != null && thrds[i] != myThrd &&
		    !thrds[i].isDaemon()) {
		try {
		    thrds[i].join();
		} catch (InterruptedException e) {
		    // just skip this thread
		}
	    }
	}
	// repeat while there are more active threads than the counted
	// daemons and the current thread.
    } while (thisGroup.activeCount() > daemons + 1);

    // now we can exit
    System.exit(status);
}
