Example usage for java.lang Runtime freeMemory

List of usage examples for java.lang Runtime freeMemory

Introduction

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

Prototype

public native long freeMemory();

Source Link

Document

Returns the amount of free memory in the Java Virtual Machine.

Usage

From source file:org.apache.hadoop.hdfs.server.namenode.Namenode2Agent.java

private static void startup() throws Exception {
    System.setProperty("PID", SystemUtils.getPid());

    try {//www .  j a  va  2 s  .c o  m
        Log4jConfigurer.initLogging(System.getProperty("location"),
                Long.parseLong(System.getProperty("refreshInterval")));
    } catch (Exception ex) {
        System.out.println("Flamingo 2 :: Cannot load Log4J configuration file. Use Resource Manager Log4J.");
    }

    StringBuilder builder = new StringBuilder();

    LOG.info("============================================================\n"
            + "Now starting Flamingo 2 - Namenode 2 Agent (" + SystemUtils.getPid() + ") ....\n"
            + "============================================================");

    builder.append(
            "    ________                _                      __  __          __                     ___                    __ \n"
                    + "   / ____/ /___ _____ ___  (_)___  ____ _____     / / / /___ _____/ /___  ____  ____     /   | ____ ____  ____  / /_\n"
                    + "  / /_  / / __ `/ __ `__ \\/ / __ \\/ __ `/ __ \\   / /_/ / __ `/ __  / __ \\/ __ \\/ __ \\   / /| |/ __ `/ _ \\/ __ \\/ __/\n"
                    + " / __/ / / /_/ / / / / / / / / / / /_/ / /_/ /  / __  / /_/ / /_/ / /_/ / /_/ / /_/ /  / ___ / /_/ /  __/ / / / /_  \n"
                    + "/_/   /_/\\__,_/_/ /_/ /_/_/_/ /_/\\__, /\\____/  /_/ /_/\\__,_/\\__,_/\\____/\\____/ .___/  /_/  |_\\__, /\\___/_/ /_/\\__/  \n"
                    + "                                /____/                                      /_/             /____/                  ");

    SortedProperties properties = new SortedProperties();
    InputStream is = ResourceUtils.getResource("classpath:/version.properties").getInputStream();
    properties.load(is);
    is.close();

    printHeader(builder, "Application Information");
    SortedProperties appProps = new SortedProperties();
    appProps.put("Application", "Flamingo Hadoop Namenode 2 Monitoring Agent");
    appProps.put("Version", properties.get("version"));
    appProps.put("Build Date", properties.get("build.timestamp"));
    appProps.put("Build Number", properties.get("build.number"));
    appProps.put("Revision Number", properties.get("revision.number"));
    appProps.put("Build Key", properties.get("build.key"));

    SortedProperties systemProperties = new SortedProperties();
    systemProperties.putAll(System.getProperties());
    appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - "
            + systemProperties.getProperty("java.vendor", UNKNOWN));
    appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN));

    print(builder, appProps);

    printHeader(builder, "Hadoop Information");

    SortedProperties hadoopProps = new SortedProperties();
    hadoopProps.put("Version", VersionInfo.getVersion()); // FIXME
    hadoopProps.put("Build Version", VersionInfo.getBuildVersion());

    print(builder, hadoopProps);

    printHeader(builder, "JVM Heap Information");

    Properties memPros = new Properties();
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    memPros.put("Total Memory", totalMemory + "MB");
    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    SortedProperties sysProps = new SortedProperties();
    for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
        sysProps.put(entry.getKey(), entry.getValue());
    }

    print(builder, sysProps);

    printHeader(builder, "System Environments");
    Map<String, String> getenv = System.getenv();
    SortedProperties envProps = new SortedProperties();
    Set<String> strings = getenv.keySet();
    for (String key : strings) {
        String message = getenv.get(key);
        envProps.put(key, message);
    }

    print(builder, envProps);

    /*
            LogbackConfigurer.initLogging("classpath:/logback.xml");
    */

    System.out.println(builder.toString());

    System.out.println(
            "================================================================================================");
    System.out.println(" Flamingo Hadoop Namenode 2 Monitoring Agent starting... ("
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ")");
    System.out.println(
            "================================================================================================");
}

From source file:gov.nih.nci.caarray.plugins.illumina.GenotypingProcessedMatrixHandler.java

static long tick(long lastTick, int line, Object proc) {
    final long now = System.currentTimeMillis();
    if (lastTick + ONE_MINUTE <= now) {
        final Runtime r = Runtime.getRuntime();
        LOG.info("...still processing around line " + line + " with " + proc + " free="
                + (r.freeMemory() / 1048576) + "/" + (r.totalMemory() / 1048576) + "MB");
        return now;
    }/*  w w w .  j  a v  a 2  s  . co m*/
    return lastTick;
}

From source file:org.b3log.latke.servlet.HTTPRequestDispatcher.java

/**
 * Dispatches with the specified context.
 * /*from w w w.j  a v  a 2 s  .com*/
 * @param context the specified specified context
 * @throws ServletException servlet exception
 * @throws IOException io exception 
 */
public static void dispatch(final HTTPRequestContext context) throws ServletException, IOException {
    final HttpServletRequest request = context.getRequest();

    String requestURI = (String) request.getAttribute(Keys.HttpRequest.REQUEST_URI);

    if (Strings.isEmptyOrNull(requestURI)) {
        requestURI = request.getRequestURI();
    }

    String method = (String) request.getAttribute(Keys.HttpRequest.REQUEST_METHOD);

    if (Strings.isEmptyOrNull(method)) {
        method = request.getMethod();
    }

    LOGGER.log(Level.FINER, "Request[requestURI={0}, method={1}]", new Object[] { requestURI, method });

    try {
        final Object processorMethodRet = RequestProcessors.invoke(requestURI, Latkes.getContextPath(), method,
                context);
    } catch (final Exception e) {
        final String exceptionTypeName = e.getClass().getName();

        LOGGER.log(Level.FINER,
                "Occured error while processing request[requestURI={0}, method={1}, exceptionTypeName={2}, errorMsg={3}]",
                new Object[] { requestURI, method, exceptionTypeName, e.getMessage() });
        if ("com.google.apphosting.api.ApiProxy$OverQuotaException".equals(exceptionTypeName)) {
            PageCaches.removeAll();

            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }

        throw new ServletException(e);
    } catch (final Error e) {
        final Runtime runtime = Runtime.getRuntime();

        LOGGER.log(Level.FINER, "Memory status[total={0}, max={1}, free={2}]",
                new Object[] { runtime.totalMemory(), runtime.maxMemory(), runtime.freeMemory() });

        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        throw e;
    }

    // XXX: processor method ret?

    final HttpServletResponse response = context.getResponse();

    if (response.isCommitted()) { // Sends rdirect or send error
        final PrintWriter writer = response.getWriter();

        writer.flush();
        writer.close();

        return;
    }

    AbstractHTTPResponseRenderer renderer = context.getRenderer();

    if (null == renderer) {
        renderer = new HTTP404Renderer();
    }

    renderer.render(context);
}

From source file:com.jaspersoft.studio.community.utils.CommunityAPIUtils.java

/**
 * @return software and hardware info.//from   w w  w .  j  a  v  a2 s .co  m
 */
public static String getHardwareSoftwareInfo() {
    BrandingInfo currBranding = JaspersoftStudioPlugin.getInstance().getBrandingInformation();
    String c = ""; //$NON-NLS-1$
    c += "Product Name: " + currBranding.getProductName() + CR; //$NON-NLS-1$
    c += "Product Version: " + currBranding.getProductVersion() + CR; //$NON-NLS-1$
    c += "Installation Path: " + getInstallationPath(currBranding.getProductMainBundleID()) + CR; //$NON-NLS-1$
    c += "Eclipse Version: " + PlatformInfo.getEclipseVersion().toString() //$NON-NLS-1$
            + CR;
    c += "Eclipse Build Name: " + PlatformInfo.getEclipseBuildName() + CR; //$NON-NLS-1$
    c += "Eclipse Build ID: " + PlatformInfo.getEclipseBuildId() + CR; //$NON-NLS-1$
    c += "IDE Name: " + PlatformInfo.getIDEName() + CR; //$NON-NLS-1$
    c += "IDE Version: " + PlatformInfo.getIDEVersionString() + CR; //$NON-NLS-1$
    c += "IDE NL: " + PlatformInfo.getIDENL() + CR; //$NON-NLS-1$
    c += "Eclipse Commands: " //$NON-NLS-1$
            + StringUtils.replaceChars(getSystemProperty("eclipse.commands"), "\n\r", " ") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            + CR;
    c += "Eclipse VM: " + getSystemProperty("eclipse.vm") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "Eclipse VM Args: " + getSystemProperty("eclipse.vmargs") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "OS Name: " + getSystemProperty("os.name") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "OS Arch: " + getSystemProperty("os.arch") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "OS Version: " + getSystemProperty("os.version") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    String linuxDescription = getLinuxDescription();
    if (!StringUtils.isEmpty(linuxDescription)) {
        c += "Linux Description: " + linuxDescription + CR; //$NON-NLS-1$
    }
    String m_mozillaResult = tryCreateMozilla();
    if (!StringUtils.isEmpty(m_mozillaResult)) {
        c += "Browser Creation Result: " + m_mozillaResult + CR; //$NON-NLS-1$
    }
    Runtime runtime = Runtime.getRuntime();
    c += "Available Processors: " + runtime.availableProcessors() + CR; //$NON-NLS-1$
    c += "Memory Max: " + runtime.maxMemory() + CR; //$NON-NLS-1$
    c += "Memory Total: " + runtime.totalMemory() + CR; //$NON-NLS-1$
    c += "Memory Free: " + runtime.freeMemory() + CR; //$NON-NLS-1$
    c += "Java Vendor: " + getSystemProperty("java.vendor") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "Java Version: " + getSystemProperty("java.version") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "Java Library Path: " + getSystemProperty("java.library.path") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    return c;
}

From source file:org.apache.solr.common.util.TestJavaBinCodec.java

static void printMem(String head) {
    System.out.println("*************" + head + "***********");
    int mb = 1024 * 1024;
    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();
    //Print used memory
    System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

    //Print free memory
    System.out.println("Free Memory:" + runtime.freeMemory() / mb);

}

From source file:fiftyfive.wicket.util.LoggingUtils.java

/**
 * Returns a string that describes the JVM's memory conditions in this
 * format: {@code 36M used, 29M free, 533M max}.
 *//*from w w w.j av a2 s .  c  om*/
public static String describeMemoryUsage() {
    Runtime runtime = Runtime.getRuntime();
    long free = runtime.freeMemory();

    return String.format("%sM used, %sM free, %sM max", (runtime.totalMemory() - free) / 1000000,
            free / 1000000, runtime.maxMemory() / 1000000);
}

From source file:org.apache.accumulo.server.gc.SimpleGarbageCollector.java

static public boolean almostOutOfMemory() {
    Runtime runtime = Runtime.getRuntime();
    return runtime.totalMemory() - runtime.freeMemory() > CANDIDATE_MEMORY_PERCENTAGE * runtime.maxMemory();
}

From source file:org.thoughtcrime.securesms.logsubmit.SubmitLogFragment.java

public static String getMemoryUsage(Context context) {
    Runtime info = Runtime.getRuntime();
    info.totalMemory();//from  w ww  .  j a v a 2  s . co m
    return String.format(Locale.ENGLISH, "%dM (%.2f%% free, %dM max)", asMegs(info.totalMemory()),
            (float) info.freeMemory() / info.totalMemory() * 100f, asMegs(info.maxMemory()));
}

From source file:com.searchbox.framework.web.SystemController.java

@ModelAttribute("jvmInfo")
public static Map<String, Object> getJvmInfo() {
    Map<String, Object> jvm = new HashMap<String, Object>();

    final String javaVersion = System.getProperty("java.specification.version", "unknown");
    final String javaVendor = System.getProperty("java.specification.vendor", "unknown");
    final String javaName = System.getProperty("java.specification.name", "unknown");
    final String jreVersion = System.getProperty("java.version", "unknown");
    final String jreVendor = System.getProperty("java.vendor", "unknown");
    final String vmVersion = System.getProperty("java.vm.version", "unknown");
    final String vmVendor = System.getProperty("java.vm.vendor", "unknown");
    final String vmName = System.getProperty("java.vm.name", "unknown");

    // Summary Info
    jvm.put("version", jreVersion + " " + vmVersion);
    jvm.put("name", jreVendor + " " + vmName);

    // details//from  ww w .j  a v  a  2s. c  o m
    Map<String, Object> java = new HashMap<String, Object>();
    java.put("vendor", javaVendor);
    java.put("name", javaName);
    java.put("version", javaVersion);
    jvm.put("spec", java);
    Map<String, Object> jre = new HashMap<String, Object>();
    jre.put("vendor", jreVendor);
    jre.put("version", jreVersion);
    jvm.put("jre", jre);
    Map<String, Object> vm = new HashMap<String, Object>();
    vm.put("vendor", vmVendor);
    vm.put("name", vmName);
    vm.put("version", vmVersion);
    jvm.put("vm", vm);

    Runtime runtime = Runtime.getRuntime();
    jvm.put("processors", runtime.availableProcessors());

    // not thread safe, but could be thread local
    DecimalFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance(Locale.ROOT));

    Map<String, Object> mem = new HashMap<String, Object>();
    Map<String, Object> raw = new HashMap<String, Object>();
    long free = runtime.freeMemory();
    long max = runtime.maxMemory();
    long total = runtime.totalMemory();
    long used = total - free;
    double percentUsed = ((double) (used) / (double) max) * 100;
    raw.put("free", free);
    mem.put("free", humanReadableUnits(free, df));
    raw.put("total", total);
    mem.put("total", humanReadableUnits(total, df));
    raw.put("max", max);
    mem.put("max", humanReadableUnits(max, df));
    raw.put("used", used);
    mem.put("used", humanReadableUnits(used, df) + " (%" + df.format(percentUsed) + ")");
    raw.put("used%", percentUsed);

    mem.put("raw", raw);
    jvm.put("memory", mem);

    // JMX properties -- probably should be moved to a different handler
    Map<String, Object> jmx = new HashMap<String, Object>();
    try {
        RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
        jmx.put("bootclasspath", mx.getBootClassPath());
        jmx.put("classpath", mx.getClassPath());

        // the input arguments passed to the Java virtual machine
        // which does not include the arguments to the main method.
        jmx.put("commandLineArgs", mx.getInputArguments());

        jmx.put("startTime", new Date(mx.getStartTime()));
        jmx.put("upTimeMS", mx.getUptime());

    } catch (Exception e) {
        LOGGER.warn("Error getting JMX properties", e);
    }
    jvm.put("jmx", jmx);
    return jvm;
}

From source file:SystemUtils.java

public static double GetAvailableMemory() {
    Runtime rt = Runtime.getRuntime();
    double availableMem;
    long maxMem, freeMem, usedJvmMem;

    usedJvmMem = rt.totalMemory();//from w w  w  .  java 2s .c om
    maxMem = rt.maxMemory();
    freeMem = rt.freeMemory();
    availableMem = (maxMem - (usedJvmMem - freeMem)) / 1048576.0d;

    return availableMem;
}