780 lines · 29.4 KB · Java
RawDownload
/* * Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.tools.jconsole; import java.awt.*;import java.awt.event.*;import java.io.*;import java.lang.management.*;import java.lang.reflect.*;import java.util.*;import java.util.concurrent.*; import javax.accessibility.*;import javax.management.*;import javax.management.openmbean.CompositeData;import javax.swing.*;import javax.swing.border.*;import javax.swing.text.*; import sun.management.*; import static sun.tools.jconsole.Formatter.*;import static sun.tools.jconsole.OverviewPanel.*;import static sun.tools.jconsole.Resources.*;import static sun.tools.jconsole.Utilities.*; @SuppressWarnings("serial")class MemoryTab extends Tab implements ActionListener, ItemListener {    JComboBox plotterChoice;    TimeComboBox timeComboBox;    JButton gcButton;     PlotterPanel plotterPanel;    JPanel bottomPanel;    HTMLPane details;    PoolChart poolChart;     ArrayList<Plotter> plotterList;    Plotter heapPlotter, nonHeapPlotter;     private MemoryOverviewPanel overviewPanel;     private static final String usedKey        = "used";    private static final String committedKey   = "committed";    private static final String maxKey         = "max";    private static final String thresholdKey   = "threshold";     private static final String usedName        = Resources.getText("Used");    private static final String committedName   = Resources.getText("Committed");    private static final String maxName         = Resources.getText("Max");    private static final String thresholdName   = Resources.getText("Threshold");     private static final Color  usedColor      = Plotter.defaultColor;    private static final Color  committedColor = null;    private static final Color  maxColor       = null;    private static final Color  thresholdColor = Color.red;     private static final String infoLabelFormat = "MemoryTab.infoLabelFormat";     /*      Hierarchy of panels and layouts for this tab:         MemoryTab (BorderLayout)             North:  topPanel (BorderLayout)                         Center: controlPanel (FlowLayout)                                    plotterChoice, timeComboBox                         East:   topRightPanel (FlowLayout)                                    gcButton             Center: plotterPanel                         Center: plotter             South:  bottomPanel (BorderLayout)                         Center: details                        East:   poolChart    */      public static String getTabName() {        return getText("Memory");    }     public MemoryTab(VMPanel vmPanel) {        super(vmPanel, getTabName());         setLayout(new BorderLayout(0, 0));        setBorder(new EmptyBorder(4, 4, 3, 4));         JPanel topPanel     = new JPanel(new BorderLayout());               plotterPanel = new PlotterPanel(null);               bottomPanel  = new JPanel(new BorderLayout());         add(topPanel,     BorderLayout.NORTH);        add(plotterPanel, BorderLayout.CENTER);         JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 20, 5));        topPanel.add(controlPanel, BorderLayout.CENTER);         // Plotter choice        plotterChoice = new JComboBox();        plotterChoice.addItemListener(this);        controlPanel.add(new LabeledComponent(getText("Chart:"),                                              getMnemonicInt("Chart:"),                                              plotterChoice));         // Range control        timeComboBox = new TimeComboBox();        controlPanel.add(new LabeledComponent(getText("Time Range:"),                                              getMnemonicInt("Time Range:"),                                              timeComboBox));         gcButton = new JButton(getText("Perform GC"));        gcButton.setMnemonic(getMnemonicInt("Perform GC"));        gcButton.addActionListener(this);        gcButton.setToolTipText(getText("Perform GC.toolTip"));        JPanel topRightPanel = new JPanel();        topRightPanel.setBorder(new EmptyBorder(0, 65-8, 0, 70));        topRightPanel.add(gcButton);        topPanel.add(topRightPanel, BorderLayout.AFTER_LINE_ENDS);         bottomPanel.setBorder(new CompoundBorder(new TitledBorder(getText("Details")),                                                  new EmptyBorder(10, 10, 10, 10)));         details = new HTMLPane();        setAccessibleName(details, getText("Details"));        bottomPanel.add(new JScrollPane(details), BorderLayout.CENTER);         poolChart = new PoolChart();        bottomPanel.add(poolChart, BorderLayout.AFTER_LINE_ENDS);    }      private void createPlotters() throws IOException {        plotterList = new ArrayList<Plotter>();         ProxyClient proxyClient = vmPanel.getProxyClient();         heapPlotter = new Plotter(Plotter.Unit.BYTES) {            public String toString() {                return Resources.getText("Heap Memory Usage");            }        };        proxyClient.addWeakPropertyChangeListener(heapPlotter);         nonHeapPlotter = new Plotter(Plotter.Unit.BYTES) {            public String toString() {                return Resources.getText("Non-Heap Memory Usage");            }        };         setAccessibleName(heapPlotter,                          getText("MemoryTab.heapPlotter.accessibleName"));        setAccessibleName(nonHeapPlotter,                          getText("MemoryTab.nonHeapPlotter.accessibleName"));         proxyClient.addWeakPropertyChangeListener(nonHeapPlotter);         heapPlotter.createSequence(usedKey,         usedName,      usedColor,      true);        heapPlotter.createSequence(committedKey,    committedName, committedColor, false);        heapPlotter.createSequence(maxKey,          maxName,       maxColor,       false);         nonHeapPlotter.createSequence(usedKey,      usedName,      usedColor,      true);        nonHeapPlotter.createSequence(committedKey, committedName, committedColor, false);        nonHeapPlotter.createSequence(maxKey,       maxName,       maxColor,       false);         plotterList.add(heapPlotter);        plotterList.add(nonHeapPlotter);         // Now add memory pools        Map<ObjectName, MBeanInfo> mBeanMap = proxyClient.getMBeans("java.lang");        Set<ObjectName> keys = mBeanMap.keySet();        ObjectName[] objectNames = keys.toArray(new ObjectName[keys.size()]);        ArrayList<PoolPlotter> nonHeapPlotters = new ArrayList<PoolPlotter>(2);        for (ObjectName objectName : objectNames) {            String type = objectName.getKeyProperty("type");            if (type.equals("MemoryPool")) {                String name = getText("MemoryPoolLabel",                                      objectName.getKeyProperty("name"));                // Heap or non-heap?                boolean isHeap = false;                AttributeList al =                    proxyClient.getAttributes(objectName,                                              new String[] { "Type" });                if (al.size() > 0) {                    isHeap = MemoryType.HEAP.name().equals(((Attribute)al.get(0)).getValue());                }                PoolPlotter poolPlotter = new PoolPlotter(objectName, name, isHeap);                proxyClient.addWeakPropertyChangeListener(poolPlotter);                 poolPlotter.createSequence(usedKey,      usedName,      usedColor,      true);                poolPlotter.createSequence(committedKey, committedName, committedColor, false);                poolPlotter.createSequence(maxKey,       maxName,       maxColor,       false);                poolPlotter.createSequence(thresholdKey, thresholdName, thresholdColor, false);                poolPlotter.setUseDashedTransitions(thresholdKey, true);                 if (isHeap) {                    plotterList.add(poolPlotter);                } else {                    // Will be added to plotterList below                    nonHeapPlotters.add(poolPlotter);                }            }        }        // Add non-heap plotters last        for (PoolPlotter poolPlotter : nonHeapPlotters) {            plotterList.add(poolPlotter);        }    }      public void itemStateChanged(ItemEvent ev) {        if (ev.getStateChange() == ItemEvent.SELECTED) {            Plotter plotter = (Plotter)plotterChoice.getSelectedItem();            plotterPanel.setPlotter(plotter);        }    }     public void gc() {        new Thread("MemoryPanel.gc") {            public void run() {                ProxyClient proxyClient = vmPanel.getProxyClient();                try {                    proxyClient.getMemoryMXBean().gc();                } catch (UndeclaredThrowableException e) {                    proxyClient.markAsDead();                } catch (IOException e) {                    // Ignore                }            }        }.start();    }     public SwingWorker<?, ?> newSwingWorker() {        return new SwingWorker<Boolean, Object>() {            private long[] used, committed, max, threshold;            private long timeStamp;            private String detailsStr;            private boolean initialRun = false;             public Boolean doInBackground() {                ProxyClient proxyClient = vmPanel.getProxyClient();                 if (plotterList == null) {                    try {                        createPlotters();                    } catch (UndeclaredThrowableException e) {                        proxyClient.markAsDead();                        return false;                    } catch (final IOException ex) {                        return false;                    }                    initialRun = true;                }                 int n = plotterList.size();                used      = new long[n];                committed = new long[n];                max       = new long[n];                threshold = new long[n];                timeStamp = System.currentTimeMillis();                int poolCount = 0;                 for (int i = 0; i < n; i++) {                    Plotter plotter = plotterList.get(i);                    MemoryUsage mu = null;                    used[i] = -1L;                    threshold[i] = -1L;                     try {                        if (plotter instanceof PoolPlotter) {                            PoolPlotter poolPlotter = (PoolPlotter)plotter;                            ObjectName objectName = poolPlotter.objectName;                            AttributeList al =                                proxyClient.getAttributes(objectName,                                                          new String[] { "Usage", "UsageThreshold" });                            if (al.size() > 0) {                                CompositeData cd = (CompositeData)((Attribute)al.get(0)).getValue();                                mu = MemoryUsage.from(cd);                                 if (al.size() > 1) {                                    threshold[i] = (Long)((Attribute)al.get(1)).getValue();                                }                            }                        } else if (plotter == heapPlotter) {                            mu = proxyClient.getMemoryMXBean().getHeapMemoryUsage();                        } else if (plotter == nonHeapPlotter) {                            mu = proxyClient.getMemoryMXBean().getNonHeapMemoryUsage();                        }                    } catch (UndeclaredThrowableException e) {                        proxyClient.markAsDead();                        return false;                    } catch (IOException ex) {                        // Skip this plotter                    }                     if (mu != null) {                        used[i]      = mu.getUsed();                        committed[i] = mu.getCommitted();                        max[i]       = mu.getMax();                    }                }                detailsStr = formatDetails();                 return true;            }             protected void done() {                try {                    if (!get()) {                        return;                    }                } catch (InterruptedException ex) {                    return;                } catch (ExecutionException ex) {                    if (JConsole.isDebug()) {                        ex.printStackTrace();                    }                    return;                }                 if (initialRun) {                    // Add Memory Pools                    for (Plotter p : plotterList) {                        plotterChoice.addItem(p);                        timeComboBox.addPlotter(p);                    }                    add(bottomPanel,  BorderLayout.SOUTH);                }                  int n = plotterList.size();                int poolCount = 0;                 for (int i = 0; i < n; i++) {                    Plotter plotter = plotterList.get(i);                    if (used[i] >= 0L) {                        if (plotter instanceof PoolPlotter) {                            plotter.addValues(timeStamp, used[i], committed[i], max[i], threshold[i]);                            if (threshold[i] > 0L) {                                plotter.setIsPlotted(thresholdKey, true);                            }                            poolChart.setValue(poolCount++, (PoolPlotter)plotter,                                               used[i], threshold[i], max[i]);                        } else {                            plotter.addValues(timeStamp, used[i], committed[i], max[i]);                        }                         if (plotter == heapPlotter && overviewPanel != null) {                            overviewPanel.getPlotter().addValues(timeStamp, used[i]);                            overviewPanel.updateMemoryInfo(used[i], committed[i], max[i]);                        }                    }                }                details.setText(detailsStr);            }        };    }     private String formatDetails() {        ProxyClient proxyClient = vmPanel.getProxyClient();        if (proxyClient.isDead()) {            return "";        }         String text = "<table cellspacing=0 cellpadding=0>";         Plotter plotter = (Plotter)plotterChoice.getSelectedItem();        if (plotter == null) {            return "";        }         //long time = plotter.getLastTimeStamp();        long time = System.currentTimeMillis();        String timeStamp = formatDateTime(time);        text += newRow(getText("Time"), timeStamp);         long used = plotter.getLastValue(usedKey);        long committed = plotter.getLastValue(committedKey);        long max = plotter.getLastValue(maxKey);        long threshold = plotter.getLastValue(thresholdKey);         text += newRow(getText("Used"), formatKBytes(used));        if (committed > 0L) {            text += newRow(getText("Committed"), formatKBytes(committed));        }        if (max > 0L) {            text += newRow(getText("Max"), formatKBytes(max));        }        if (threshold > 0L) {            text += newRow(getText("Usage Threshold"), formatKBytes(threshold));        }         try {            Collection<GarbageCollectorMXBean> garbageCollectors =                proxyClient.getGarbageCollectorMXBeans();             boolean descPrinted = false;            for (GarbageCollectorMXBean garbageCollectorMBean : garbageCollectors) {                String gcName = garbageCollectorMBean.getName();                long gcCount = garbageCollectorMBean.getCollectionCount();                long gcTime = garbageCollectorMBean.getCollectionTime();                String str = getText("GC time details", justify(formatTime(gcTime), 14),                                     gcName,                                     String.format("%,d",gcCount));                if (!descPrinted) {                    text += newRow(getText("GC time"), str);                    descPrinted = true;                } else {                    text += newRow(null, str);                }           }        } catch (IOException e) {        }         return text;    }     public void actionPerformed(ActionEvent ev) {        Object src = ev.getSource();        if (src == gcButton) {            gc();        }    }     private class PoolPlotter extends Plotter {        ObjectName objectName;        String name;        boolean isHeap;        long value, threshold, max;        int barX;         public PoolPlotter(ObjectName objectName, String name, boolean isHeap) {            super(Plotter.Unit.BYTES);             this.objectName = objectName;            this.name       = name;            this.isHeap     = isHeap;             setAccessibleName(this,                              getText("MemoryTab.poolPlotter.accessibleName",                                      name));        }          public String toString() {            return name;        }    }     private class PoolChart extends BorderedComponent                            implements Accessible, MouseListener {        final int height       = 150;        final int leftMargin   =  50;        final int rightMargin  =  23;        final int bottomMargin =  35;        final int barWidth     =  22;        final int barGap       =   3;        final int groupGap     =   8;        final int barHeight    = height * 2 / 3;         final Color greenBar           = new Color(100, 255, 100);        final Color greenBarBackground = new Color(210, 255, 210);        final Color redBarBackground   = new Color(255, 210, 210);         Font smallFont = null;         ArrayList<PoolPlotter> poolPlotters = new ArrayList<PoolPlotter>(5);         int nHeapPools    = 0;        int nNonHeapPools = 0;        Rectangle heapRect    = new Rectangle(leftMargin,            height - bottomMargin + 6, barWidth, 20);        Rectangle nonHeapRect = new Rectangle(leftMargin + groupGap, height - bottomMargin + 6, barWidth, 20);

Lines 1–500 of 780.