Criar um visualizador de memória em uso! Alguém conhece o caminho?

5 respostas
Zakim

Bom dia a todos.

Preciso criar um visualizador de memória que mostre dentro da minha aplicação, quanto de memória está sendo consumido para
a pelo programa.

Acredito que deve existir algum comando milagroso que me faça boa parte do serviço. Alguém o conhece? Caso não exista :frowning: , poderiam me dar algumas dicas de como posso construir um?

obrigado!

5 Respostas

davidtiagoconceicao

Dê uma olhada na classe Runtime, ela tem alguns métodos que podem te ajudar.
Exemplo de código que escrevi para alguns testes:

public static void main(String args[]) {
		Runtime rt = Runtime.getRuntime();
		System.out.println("Memória livre " + rt.freeMemory());
		System.out.println("Máximo memória: " + rt.maxMemory());
		System.out.println("Número de processadores: " + rt.availableProcessors());
	}
Zakim

valeu davidtiagoconceicao.

obrigado!

:stuck_out_tongue:

davidtiagoconceicao

Opa, de nada.

Não sei se era essa a classe milagrosa que você esperava, mas tudo bem. uahauha
Dúvidas poste aí.
Valeu!

ViniGodoy

Aqui está a classe que criamos aqui na empresa para isso. Ela nada mais é que uma barra de progresso, que mostra a quantidade de memória disponível e utilizada.
Ela ainda possui um listener, caso vc queira ouvir que a memória está abaixo de um determinado limite (útil para logs).

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JProgressBar;

public class MemoryBar extends JProgressBar {
    final int MAX_MEGA = (int) ((float) Runtime.getRuntime().maxMemory() / 1048576);
    private int lowMemory = 10;
    private Thread thread = null;
    private final MemoryReader reader = new MemoryReader();

    private List<MemoryBarListener> listeners = new ArrayList<MemoryBarListener>();

    public MemoryBar() {
        setMaximum(100);
        setStringPainted(true);
        setString("");
        start();
    }

    /**
     * Sets the low memory limit. Below that, low memory events will be fired.
     * 
     * @param lowMemory Memory limit, in megabytes.
     */
    public void setLowMemory(int lowMemory) {
        this.lowMemory = lowMemory;
    }

    /**
     * Sets the low memory percent, relative to the maximum memory. Below that,
     * low memory events will be fired.
     * 
     * @param lowMemory Memory limit, in megabytes.
     */
    public void setLowMemoryPercent(double lowMemory) {
        this.lowMemory = (int) (MAX_MEGA * lowMemory / 100);
    }

    public void start() {
        if (thread != null)
            return;
        thread = new Thread(reader, "Memory bar thread");
        thread.setDaemon(true);
        thread.start();
    }

    public void stop() {
        if (thread == null)
            return;
        thread.interrupt();
        thread = null;
    }

    public synchronized void addListener(MemoryBarListener listener) {
        listeners.add(listener);
    }

    public synchronized void removeListener(MemoryBarListener listener) {
        listeners.remove(listener);
    }

    private synchronized void fireLowMemory(double usedMega) {
        LowMemoryEvent lme = new LowMemoryEvent(this, usedMega, MAX_MEGA);
        for (MemoryBarListener listener : listeners)
            listener.lowMemory(lme);
    }

    private class MemoryReader implements Runnable {
        public void run() {
            try {
                while (!Thread.interrupted()) {
                    long total = Runtime.getRuntime().totalMemory();
                    long free = Runtime.getRuntime().freeMemory();
                    double usedMega = (total - free) / 1048576.0;
                    updateBar(usedMega);

                    if (MAX_MEGA - usedMega < lowMemory)
                        fireLowMemory(usedMega);
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {}
        }

        private void updateBar(final double usedMega) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    setValue((int) (usedMega * 100.0 / MAX_MEGA));
                    setString(String.format("%.1fM of %dM", usedMega, MAX_MEGA));
                }
            });
        }
    }
}

Evento de pouca memória:

import java.util.Calendar;
import java.util.EventObject;

public class LowMemoryEvent extends EventObject {
    private Calendar timestamp;
    private double used;
    private int total;
    
    public LowMemoryEvent(MemoryBar source, double used, int max) {
        super(source);
        this.timestamp = Calendar.getInstance();
        this.used = used;
        this.total = max;
    }
    
    public Calendar getTimestamp() {
        return timestamp;
    }
    
    public double getUsed() {
        return used;
    }
    
    public int getTotal() {
        return total;
    }
    
    @Override
    public MemoryBar getSource() {
        return (MemoryBar)super.getSource();
    }
    
    @Override
    public String toString() {        
        return String.format("LOW MEMORY: Used: %.1f  Total: %d");
    }
}

Listener:

public interface MemoryBarListener { void lowMemory(LowMemoryEvent e); }

davidtiagoconceicao

Excelente exemplo ViniGodoy. Fiz alguns testes e é realmente bem interessante.

Obrigado! (Y)

Criado 18 de fevereiro de 2009
Ultima resposta 19 de fev. de 2009
Respostas 5
Participantes 3