/*
 * File:     MPIThreadGroup.java
 * Project:  MPI Linguistic Application
 * Date:     03 April 2006
 *
 * Copyright (C) 2001-2006  Max Planck Institute for Psycholinguistics
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * Created on Feb 4, 2004
 * $Id: MPIThreadGroup.java,v 1.1 2004/03/30 12:48:10 wouthuij Exp $
 */
package mpi.library;


/**
 * A ThreadGroup implementation that overrides the
 * <code>uncaughtException</code> method in order to act appropriately in case
 * of a <code>OutOfMemoryError</code>. The user will be notified with a
 * dialog, and the application will quit.
 *
 * @author Wouter Huijnink
 */
public class MPIThreadGroup extends ThreadGroup {
    /**
     * Creates a new instance
     *
     * @param name The name of this instance.
     */
    public MPIThreadGroup(String name) {
        super(name);

        //Auto-generated constructor stub
    }

    /**
     * Creates a new instance
     *
     * @param parent The parent ThreadGroup of this instance.
     * @param name The name of this instance.
     */
    public MPIThreadGroup(ThreadGroup parent, String name) {
        super(parent, name);

        //Auto-generated constructor stub
    }

    /**
     * Returns a MemoryMonitor instance.
     *
     * @param minAvailable If available memory drops below this value, a
     *        warning will be issued by the monitor.
     *
     * @return A MemoryMonitor instance.
     */
    public Thread getMonitorThread(long minAvailable) {
        return new MemoryMonitor(this, minAvailable);
    }

    /**
     * If the uncaught exception is a OutOfMemoryException, the user will be
     * notified and the application will be aborted by calling Syste.exit().
     *
     * @see java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
     *      java.lang.Throwable)
     */
    public void uncaughtException(Thread t, Throwable thr) {
        //System.out.println("uncaughtException: " + thr);
        if (thr instanceof OutOfMemoryError) {
            javax.swing.JOptionPane.showMessageDialog(null,
                "Not enough memory - Application will quit.",
                "Not enough memory", javax.swing.JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        } else {
            System.err.println("Uncaught exception in thread " + t + ": " +
                thr);
            thr.printStackTrace();
        }
    }

    /**
     * This thread will monitor the availability of memory.  If the available
     * memory drops below the amount specified at initialization,  the user is
     * warned that memory is low.
     *
     * @author Wouter Huijnink
     */
    private static class MemoryMonitor extends Thread {
        /** The Runtime that is being monitored. */
        private Runtime runtime;

        /**
         * The maximum amount of memory that can be allocated by the JVM in the
         * current Runtime.
         */
        private long maxMemory;

        /**
         * If available memory drops below this amount, the user will be
         * notified.
         */
        private long minAvailable = 2000000;

        /** The previous amount of mememory available. */
        private long lastAvailable;

        /**
         * The number of milliseconds this thread should sleep before checking
         * memory again
         */
        private long sleepTime = 500;

        /** Flag indicating whether a garbage collection occurred. */
        private boolean gcOccurred = false;

        /** The text that wil be displayed when a warning is issued. */
        private String warning = "Running low on memory! It may be wise to close some windows.";

        /**
         * Creates a new MemoryMonitor object.
         *
         * @param tg DOCUMENT ME!
         * @param minAvailable DOCUMENT ME!
         */
        private MemoryMonitor(ThreadGroup tg, long minAvailable) {
            super(tg, "memory monitor");
            this.minAvailable = minAvailable;
            runtime = Runtime.getRuntime();
            maxMemory = runtime.maxMemory();
            lastAvailable = getAvailableMemory();
            System.out.println("New MemoryMonitor:\nsleepTime=" + sleepTime +
                "\nminAvailable=" + minAvailable);
        }

        /**
         * Returns a new instance of this class.
         *
         * @param tg The ThreadGroup to which this instance belongs.
         * @param minAvailable The minimal amount of memory that should be
         *        available before a warning is issued.
         *
         * @return A new MemoryMonitor instance.
         */
        public static MemoryMonitor getInstance(ThreadGroup tg,
            long minAvailable) {
            return new MemoryMonitor(tg, minAvailable);
        }

        /**
         * Set the time between checks.
         *
         * @param sleepTime New value for sleepTime.
         */
        public void setSleepTime(long sleepTime) {
            this.sleepTime = sleepTime;
        }

        /**
         * Adjusts the text htat will be displayed when a warnig is issued.
         *
         * @param warning New value for warning.
         */
        public void setWarning(String warning) {
            this.warning = warning;
        }

        /**
         * Monitors the available memory. If the availability drops below
         * minAvailable,  a warning is provided to the user. The user can
         * indicate whether continued  monitoring is desired, or whether the
         * monitor should quit.
         *
         * @see java.lang.Runnable#run()
         */
        public void run() {
            boolean stop = false;

            //int counter = 0;
            while (!stop && !isInterrupted()) {
                try {
                    long available = getAvailableMemory();

                    if (available > lastAvailable) {
                        gcOccurred = true;
                    }

                    lastAvailable = available;

                    if ((available <= minAvailable) && gcOccurred) {
                        Object[] options = new String[] {
                                "OK", "Don't warn me again"
                            };

                        int answer = javax.swing.JOptionPane.showOptionDialog(null,
                                warning, "Low on memory",
                                javax.swing.JOptionPane.OK_CANCEL_OPTION,
                                javax.swing.JOptionPane.WARNING_MESSAGE, null,
                                options, options[1]);

                        if (answer != javax.swing.JOptionPane.OK_OPTION) {
                            stop = true; //stop monitoring
                        }

                        gcOccurred = false;
                    }

                    /*if(counter % 10 == 0) {
                       mem();//display current memory status (for DEBUG purposes)
                       }
                       counter++;*/
                    sleep(sleepTime);
                } catch (InterruptedException e) {
                    System.err.println(this + " was interrupted - " + e); //LOG ERROR

                    stop = true;
                }
            }

            System.out.println("MemoryMonitor quits.");

            return;
        }

        /**
         * Returns the currently available amount of memory.
         *
         * @return The currently available amount of memory.
         */
        private long getAvailableMemory() {
            return (maxMemory - (runtime.totalMemory() - runtime.freeMemory()));
        }

        /**
         * Debug method - displays maximum available memory, currently
         * allocated memory, and amount of memory in use.
         */
        private void mem() {
            System.out.println("Max memory: " +
                formatNumber(runtime.maxMemory()));
            System.out.println("Allocated memory: " +
                formatNumber(runtime.totalMemory()));
            System.out.println("In use: " +
                formatNumber(runtime.totalMemory() - runtime.freeMemory()) +
                "\n");
        }

        /**
         * Debug method - helps to format long.
         *
         * @param nr The long number that should be formatted.
         *
         * @return A formatted String representing the long parameter.
         */
        private static String formatNumber(long nr) {
            return java.text.NumberFormat.getInstance(new java.util.Locale("nl"))
                                         .format(nr);
        }
    }
}
