// GcStat.java
// $Id: GcStat.java,v 1.3 1996/07/20 00:01:02 abaird Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.status ;

import w3c.www.http.*;
import w3c.jigsaw.http.* ;
import w3c.jigsaw.resources.*;
import w3c.jigsaw.html.HtmlGenerator ;

/**
 * This class implements a GC counter.
 * It counts the number of GC that has occured since the system was brought up.
 */

class GcCounter {
    private static int count= 0 ;

    private static synchronized void incrCounter() {
	count++ ;
    }

    private static synchronized int getCount() {
	return count ;
    }

    public static int getGcCount() {
	System.runFinalization() ;
	return getCount() ;
    }

    public void finalize() {
	incrCounter() ;
	new GcCounter() ;
    }

    static {
	new GcCounter() ;
    }
}

/**
 * Each time you get this resource, it fill run the GC.
 */

public class GcStat extends HTTPResource {
    protected Runtime runtime = null ;

    /**
     * Dump the current memory status.
     * @param request The request we are to reply to.
     */

    protected Reply dumpMemoryStatus (Request request) {
	HtmlGenerator g = new HtmlGenerator ("Memory Status") ;
	g.meta("Refresh", "5") ;
	g.append("<h1>Memory status</h1>") ;
	g.append("<p>Free memory : "+runtime.freeMemory()) ;
	g.append("<p>Total memory: "+runtime.totalMemory()) ;
	g.append("<p>GC count: "+GcCounter.getGcCount()) ;
	g.append("<hr>") ;
	// Reply back:
	Reply  reply = request.makeReply(HTTP.OK) ;
	reply.setStream (g) ;
	return reply ;
    }

    /**
     * Perform a GC and display memory status.
     * @param request The request to handle.
     */
     
    public Reply get (Request request) {
	return dumpMemoryStatus(request) ;
    }

    /**
     * Initialize the thread lister.
     * Just get a pointer to our runtime object.
     * @param values The default attribute values.
     */

    public void initialize(Object values[]) {
	super.initialize(values) ;
	runtime = Runtime.getRuntime() ;
    }
    
}
