Example usage for java.lang Runtime maxMemory

List of usage examples for java.lang Runtime maxMemory

Introduction

In this page you can find the example usage for java.lang Runtime maxMemory.

Prototype

public native long maxMemory();

Source Link

Document

Returns the maximum amount of memory that the Java virtual machine will attempt to use.

Usage

From source file:xc.mst.utils.TimingStats.java

private void outputMemory(boolean runGC) {
    if (runGC) {//from  w  w w  . j ava 2 s  .  c o m
        System.gc();
    }
    Runtime r = Runtime.getRuntime();
    long maxMem = r.maxMemory() / 1048576;
    long totalMem = r.totalMemory() / 1048576;

    long freeBytes = r.freeMemory();
    long freeMem = freeBytes / 1048576;

    long usedMem = totalMem - freeMem;
    long memIncrease = usedMem - memUsedAtLastReset;
    memUsedAtLastReset = usedMem;

    LOG.debug("");
    LOG.debug("Free  memory: " + StringUtils.leftPad(freeMem + "", 7) + " MB.");
    LOG.debug("Used  memory: " + StringUtils.leftPad(usedMem + "", 7) + " MB.");
    LOG.debug("Increased by: " + StringUtils.leftPad(memIncrease + "", 7) + " MB.");
    LOG.debug("Total memory: " + StringUtils.leftPad(totalMem + "", 7) + " MB.");
    LOG.debug("Max'm memory: " + StringUtils.leftPad(maxMem + "", 7) + " MB.");

    //double percentageUsed = ((double) usedMem) / maxMem;
    //System.out.println("percentageUsed = " + percentageUsed);
    //MemoryWarningSystem.setPercentageUsageThreshold(0.8);  // 80%
}

From source file:edu.ku.brc.ui.FeedBackSender.java

/**
 * Creates an array of POST method parameters to send with the version checking / usage tracking connection.
 * //  ww  w .  j a  va2  s. co  m
 * @param item the item to fill
 * @return an array of POST parameters
 */
protected NameValuePair[] createPostParameters(final FeedBackSenderItem item) {
    Vector<NameValuePair> postParams = new Vector<NameValuePair>();
    try {
        postParams.add(new NameValuePair("bug", item.getBug())); //$NON-NLS-1$
        postParams.add(new NameValuePair("class_name", item.getClassName())); //$NON-NLS-1$
        postParams.add(new NameValuePair("comments", item.getComments())); //$NON-NLS-1$
        postParams.add(new NameValuePair("stack_trace", item.getStackTrace())); //$NON-NLS-1$
        postParams.add(new NameValuePair("task_name", item.getTaskName())); //$NON-NLS-1$
        postParams.add(new NameValuePair("title", item.getTitle())); //$NON-NLS-1$

        // get the install ID
        String installID = UsageTracker.getInstallId();
        postParams.add(new NameValuePair("id", installID)); //$NON-NLS-1$

        Runtime runtime = Runtime.getRuntime();
        Long usedMemory = runtime.maxMemory() - (runtime.totalMemory() + runtime.freeMemory());
        Long maxMemory = runtime.maxMemory();

        // get the OS name and version
        postParams.add(new NameValuePair("os_name", System.getProperty("os.name"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("os_version", System.getProperty("os.version"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("java_version", System.getProperty("java.version"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("java_vendor", System.getProperty("java.vendor"))); //$NON-NLS-1$ //$NON-NLS-2$
        postParams.add(new NameValuePair("max_memory", maxMemory.toString())); //$NON-NLS-1$
        postParams.add(new NameValuePair("used_memory", usedMemory.toString())); //$NON-NLS-1$

        Properties props = item.getProps();
        if (props != null) {
            for (Object key : props.keySet()) {
                postParams.add(new NameValuePair(key.toString(), props.getProperty(key.toString()))); //$NON-NLS-1$
            }
        }

        //if (!UIRegistry.isRelease()) // For Testing Only
        {
            postParams.add(new NameValuePair("user_name", System.getProperty("user.name"))); //$NON-NLS-1$
            try {
                postParams.add(new NameValuePair("ip", InetAddress.getLocalHost().getHostAddress())); //$NON-NLS-1$
            } catch (UnknownHostException e) {
            }
        }

        String resAppVersion = UIRegistry.getAppVersion();
        if (StringUtils.isEmpty(resAppVersion)) {
            resAppVersion = "Unknown";
        }
        postParams.add(new NameValuePair("app_version", resAppVersion)); //$NON-NLS-1$

        Vector<NameValuePair> extraStats = collectionSecondaryInfo(item);
        if (extraStats != null) {
            postParams.addAll(extraStats);
        }

        // create an array from the params
        NameValuePair[] paramArray = new NameValuePair[postParams.size()];
        for (int i = 0; i < paramArray.length; ++i) {
            paramArray[i] = postParams.get(i);
        }

        return paramArray;

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:com.kyne.webby.bukkit.RTKModuleSocket.java

private void getInfos(final Map<String, Object> responseParams) {
    final List<WebbyPlayer> playerList = new ArrayList<WebbyPlayer>();
    for (final Player player : Bukkit.getOnlinePlayers()) {
        playerList.add(new WebbyPlayer(player.getName(), player.isOp()));
    }//from   w  ww. ja  va 2 s .c  o m
    final Runtime runtime = Runtime.getRuntime();
    final long freeMemory = runtime.freeMemory();
    final long totalMemory = runtime.totalMemory();
    final long maxMemory = runtime.maxMemory();
    final int mb = 1024 * 1024;

    final ServerInfos serverInfos = new ServerInfos(Bukkit.getVersion(), Bukkit.getMaxPlayers(),
            playerList.size(), playerList, freeMemory / mb, totalMemory / mb, maxMemory / mb);
    responseParams.put("DATA", serverInfos);
}

From source file:nz.govt.natlib.ndha.manualdeposit.dialogs.About.java

@SuppressWarnings("unchecked")
private void startup() {
    try {/*from  w ww . j  a  va 2 s  .  co m*/
        try {
            theFormControl = new FormControl(this, theSettingsPath);
        } catch (Exception ex) {
            LOG.error("Error loading form parameters", ex);
        }
        ClassLoader cLoader = Thread.currentThread().getContextClassLoader();
        Toolkit kit = Toolkit.getDefaultToolkit();
        Package p = this.getClass().getPackage();
        lblVersion.setText(p.getImplementationVersion());
        if (new File(theLogoFileName).exists()) {
            theLogo = kit.getImage(theLogoFileName);
        } else {
            java.net.URL imageURL = cLoader.getResource(theLogoFileName);
            if (imageURL != null) {
                theLogo = kit.getImage(imageURL);
            }
        }
        if (theLogo != null) {
            lblBuildNo.setForeground(Color.white);
            lblBuildNoLabel.setForeground(Color.white);
            //lblHeader.setForeground(Color.white);
            lblVersion.setForeground(Color.white);
            lblVersionLabel.setForeground(Color.white);
            paintImage();
        }
        //String manifestFileName = "/META-INF/MANIFEST.MF";
        Class cls = this.getClass();

        String className = cls.getSimpleName();
        String classFileName = className + ".class";
        String pathToThisClass = cls.getResource(classFileName).toString();
        int mark = pathToThisClass.indexOf("!");
        String pathToManifest = pathToThisClass.substring(0, mark + 1);
        if (!pathToManifest.equals("")) {
            pathToManifest += "/META-INF/MANIFEST.MF";
            LOG.debug("Path to manifest: " + pathToManifest);
            Manifest mf = new Manifest(new URL(pathToManifest).openStream());
            if (mf != null) {
                Attributes attr = mf.getMainAttributes();
                String attrVersion = "Implementation-Version";
                String attrBuild = "Implementation-Build";
                String version = attr.getValue(attrVersion);
                String build = attr.getValue(attrBuild);
                this.lblVersion.setText(version);
                this.lblBuildNo.setText(build);
            }
        }
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        LOG.debug("free memory: " + freeMemory / 1024);
        LOG.debug("allocated memory: " + allocatedMemory / 1024);
        LOG.debug("max memory: " + maxMemory / 1024);
        LOG.debug("total free memory: " + (freeMemory + (maxMemory - allocatedMemory)) / 1024);
    } catch (IOException ex) {
        ex.printStackTrace();
        LOG.error(ex.getMessage(), ex);
    }
}

From source file:com.ibm.bluemix.mobilestarterkit.service.ServiceAPI.java

@Path("/autoscaling")
@POST/*  w  w w .  j a  va2 s . co  m*/
public String autoScalingByMem(String param) {
    try {
        JSONObject meta = new JSONObject(param);

        Runtime rt = Runtime.getRuntime();
        int mem_usage = (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0));

        String action = meta.getString("action");

        if ("mem_up".equalsIgnoreCase(action)) {
            // 10M  . Out of memory ?  ?.
            for (int i = 0; i < 10; i++) {
                byte b[] = new byte[1048576];
                v.add(b);
            }
        } else if ("mem_safe_up".equalsIgnoreCase(action) && mem_usage < 90) {
            //   90% ? ?, 10M . OOM 
            for (int i = 0; i < 10; i++) {
                byte b[] = new byte[1048576];
                v.add(b);
            }
        } else if ("mem_reset".equalsIgnoreCase(action)) {
            //  ? 
            v = new Vector();
            rt.gc();
        }
        String msg = "Max " + (rt.maxMemory() / 1000) + " KB  Total used : " + (rt.totalMemory() / 1000)
                + " KB  Free : " + (rt.freeMemory() / 1000) + " KB  "
                + (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0)) + " %";
        System.out.println(msg);
        return msg;

    } catch (JSONException e) {

        e.getStackTrace();
        return "Failed";

    }
}

From source file:com.amazonaws.metrics.internal.cloudwatch.MachineMetricFactory.java

private void addMemoryMetrics(List<MetricDatum> targetList, Set<MachineMetric> customSet) {
    Runtime rt = Runtime.getRuntime();
    long totalMem = rt.totalMemory();
    long freeMem = rt.freeMemory();
    long usedMem = totalMem - freeMem;
    long spareMem = rt.maxMemory() - usedMem;
    List<Long> values = Arrays.asList(totalMem, freeMem, usedMem, spareMem);
    MetricValues metricValues = memoryMetricValues(customSet, values);
    addMetrics(targetList, metricValues, StandardUnit.Bytes);
}

From source file:com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java

private String getMemoryStats() {
    final Runtime rt = Runtime.getRuntime();
    final long free = rt.freeMemory() / 1024;
    final long total = rt.totalMemory() / 1024;
    final long max = rt.maxMemory() / 1024;
    final long used = total - free;
    final String format = "used: {0,number,0}K, free: {1,number,0}K, total: {2,number,0}K, max: {3,number,0}K";
    return MessageFormat.format(format, Long.valueOf(used), Long.valueOf(free), Long.valueOf(total),
            Long.valueOf(max));/*from w  ww.ja v a 2 s .co m*/
}

From source file:org.ngrinder.operation.cotroller.StatisticsController.java

/**
 * Get current jvm stat//from w  w  w  .j a v  a  2 s  .com
 * 
 * @return map for jvm used/free/total/max
 */
private Map<String, Long> getJVMStat() {
    Runtime runtime = Runtime.getRuntime();

    Map<String, Long> stat = new HashMap<String, Long>();
    stat.put("used", runtime.totalMemory() - runtime.freeMemory());
    stat.put("free", runtime.freeMemory());
    stat.put("total", runtime.totalMemory());
    stat.put("max", runtime.maxMemory());

    return stat;
}

From source file:com.github.lpezet.antiope.metrics.aws.MachineMetricFactory.java

private void addMemoryMetrics(List<MetricDatum> pTargetList, Set<MachineMetric> pCustomSet) {
    Runtime rt = Runtime.getRuntime();
    long oTotalMem = rt.totalMemory();
    long oFreeMem = rt.freeMemory();
    long oUsedMem = oTotalMem - oFreeMem;
    long oSpareMem = rt.maxMemory() - oUsedMem;
    List<Long> oValues = Arrays.asList(oTotalMem, oFreeMem, oUsedMem, oSpareMem);
    MetricValues oMetricValues = memoryMetricValues(pCustomSet, oValues);
    addMetrics(pTargetList, oMetricValues, StandardUnit.Bytes);
}

From source file:com.tesora.dve.common.PatternLayoutWithHeader.java

@Override
public String getHeader() {
    Runtime runtime = Runtime.getRuntime();

    StringBuffer header = new StringBuffer();
    header.append(StringUtils.repeat("-", 80));
    header.append("\nLog Started : ").append(new Date().toString());
    header.append("\nBuild Info  : ").append(PELogUtils.getBuildVersionString(true));
    header.append("\nMemory      : max=").append(String.format("%,d", runtime.maxMemory())).append(" total=")
            .append(String.format("%,d", runtime.totalMemory())).append(" free=")
            .append(String.format("%,d", runtime.freeMemory()));
    header.append("\nProcessors  : ").append(runtime.availableProcessors());
    try {/*from w  w  w  .  j av a 2 s  .  c om*/
        header.append("\nHost        : ").append(InetAddress.getLocalHost());
    } catch (UnknownHostException e) {
        header.append("\nHost        : unknown");
    }
    header.append("\n");
    return header.toString();
}