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: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/* w ww .  j  av a 2  s.  c om*/
    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: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  . c  om
    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:co.aikar.timings.TimingsExport.java

/**
 * Checks if any pending reports are being requested, and builds one if needed.
 *//*from   ww  w. j a  va2  s.  c  om*/
static void reportTimings() {
    if (requestingReport.isEmpty()) {
        return;
    }
    TimingsReportListener listeners = new TimingsReportListener(requestingReport);
    listeners.addConsoleIfNeeded();

    requestingReport.clear();
    long now = System.currentTimeMillis();
    final long lastReportDiff = now - lastReport;
    if (lastReportDiff < 60000) {
        listeners.sendMessage(ChatColor.RED + "Please wait at least 1 minute in between Timings reports. ("
                + (int) ((60000 - lastReportDiff) / 1000) + " seconds)");
        listeners.done();
        return;
    }
    final long lastStartDiff = now - TimingsManager.timingStart;
    if (lastStartDiff < 180000) {
        listeners.sendMessage(ChatColor.RED
                + "Please wait at least 3 minutes before generating a Timings report. Unlike Timings v1, v2 benefits from longer timings and is not as useful with short timings. ("
                + (int) ((180000 - lastStartDiff) / 1000) + " seconds)");
        listeners.done();
        return;
    }
    listeners.sendMessage(ChatColor.GREEN + "Preparing Timings Report...");
    lastReport = now;
    Map parent = createObject(
            // Get some basic system details about the server
            pair("version", Bukkit.getVersion()), pair("maxplayers", Bukkit.getMaxPlayers()),
            pair("start", TimingsManager.timingStart / 1000), pair("end", System.currentTimeMillis() / 1000),
            pair("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000));
    if (!TimingsManager.privacy) {
        appendObjectData(parent, pair("server", Bukkit.getServerName()),
                pair("motd", Bukkit.getServer().getMotd()),
                pair("online-mode", Bukkit.getServer().getOnlineMode()),
                pair("icon", Bukkit.getServer().getServerIcon().getData()));
    }

    final Runtime runtime = Runtime.getRuntime();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

    parent.put("system", createObject(pair("timingcost", getCost()),
            pair("name", System.getProperty("os.name")), pair("version", System.getProperty("os.version")),
            pair("jvmversion", System.getProperty("java.version")), pair("arch", System.getProperty("os.arch")),
            pair("maxmem", runtime.maxMemory()), pair("cpu", runtime.availableProcessors()),
            pair("runtime", ManagementFactory.getRuntimeMXBean().getUptime()),
            pair("flags", StringUtils.join(runtimeBean.getInputArguments(), " ")),
            pair("gc",
                    toObjectMapper(ManagementFactory.getGarbageCollectorMXBeans(),
                            input -> pair(input.getName(),
                                    toArray(input.getCollectionCount(), input.getCollectionTime()))))));

    Set<Material> tileEntityTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();

    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
        tileEntityTypeSet.addAll(timingHistory.tileEntityTypeSet);
        entityTypeSet.addAll(timingHistory.entityTypeSet);
        history[i++] = timingHistory;
    }

    history[i] = new TimingHistory(); // Current snapshot
    tileEntityTypeSet.addAll(history[i].tileEntityTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);

    Map handlers = createObject();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (TimingHandler id : group.handlers) {
            if (!id.isTimed() && !id.isSpecial()) {
                continue;
            }
            handlers.put(id.id, toArray(group.id, id.name));
        }
    }

    parent.put("idmap",
            createObject(
                    pair("groups",
                            toObjectMapper(
                                    TimingIdentifier.GROUP_MAP.values(), group -> pair(group.id, group.name))),
                    pair("handlers", handlers), pair(
                            "worlds",
                            toObjectMapper(TimingHistory.worldMap.entrySet(),
                                    input -> pair(input.getValue(), input.getKey()))),
                    pair("tileentity",
                            toObjectMapper(tileEntityTypeSet, input -> pair(input.getId(), input.name()))),
                    pair("entity",
                            toObjectMapper(entityTypeSet, input -> pair(input.getTypeId(), input.name())))));

    // Information about loaded plugins

    parent.put("plugins",
            toObjectMapper(Bukkit.getPluginManager().getPlugins(), plugin -> pair(plugin.getName(),
                    createObject(pair("version", plugin.getDescription().getVersion()),
                            pair("description",
                                    String.valueOf(plugin.getDescription().getDescription()).trim()),
                            pair("website", plugin.getDescription().getWebsite()),
                            pair("authors", StringUtils.join(plugin.getDescription().getAuthors(), ", "))))));

    // Information on the users Config

    parent.put("config", createObject(pair("bukkit", mapAsJSON(Bukkit.spigot().getConfig(), null))));

    new TimingsExport(listeners, parent, history).start();
}

From source file:org.spigotmc.timings.TimingsExport.java

/**
 * Builds an XML report of the timings to be uploaded for parsing.
 *
 * @param sender Who to report to//from  w  w w.  j  a  v a 2s.c o m
 */
static void reportTimings(CommandSender sender) {
    Map parent = createObject(
            // Get some basic system details about the server
            pair("version", Bukkit.getVersion()), pair("maxplayers", Bukkit.getMaxPlayers()),
            pair("start", TimingsManager.timingStart / 1000), pair("end", System.currentTimeMillis() / 1000),
            pair("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000));
    if (!TimingsManager.privacy) {
        appendObjectData(parent, pair("server", Bukkit.getServerName()),
                pair("motd", Bukkit.getServer().getMotd()),
                pair("online-mode", Bukkit.getServer().getOnlineMode()),
                pair("icon", Bukkit.getServer().getServerIcon().getData()));
    }

    final Runtime runtime = Runtime.getRuntime();

    parent.put("system",
            createObject(pair("timingcost", getCost()), pair("name", System.getProperty("os.name")),
                    pair("version", System.getProperty("os.version")),
                    pair("arch", System.getProperty("os.arch")), pair("totalmem", runtime.totalMemory()),
                    pair("usedmem", runtime.totalMemory() - runtime.freeMemory()),
                    pair("maxmem", runtime.maxMemory()), pair("cpu", runtime.availableProcessors()),
                    pair("runtime", (System.currentTimeMillis() / 1000) - TimingsManager.SERVER_START)));

    Set<Material> tileEntityTypeSet = Sets.newHashSet();
    Set<EntityType> entityTypeSet = Sets.newHashSet();

    int size = HISTORY.size();
    TimingHistory[] history = new TimingHistory[size + 1];
    int i = 0;
    for (TimingHistory timingHistory : HISTORY) {
        tileEntityTypeSet.addAll(timingHistory.tileEntityTypeSet);
        entityTypeSet.addAll(timingHistory.entityTypeSet);
        history[i++] = timingHistory;
    }

    history[i] = new TimingHistory(); // Current snapshot
    tileEntityTypeSet.addAll(history[i].tileEntityTypeSet);
    entityTypeSet.addAll(history[i].entityTypeSet);

    Map handlers = createObject();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (TimingHandler id : group.handlers) {
            if (!id.timed && !id.isSpecial()) {
                continue;
            }
            handlers.put(id.id, toArray(group.id, id.name));
        }
    }

    parent.put("idmap", createObject(pair("groups", toObjectMapper(TimingIdentifier.GROUP_MAP.values(),
            new Function<TimingIdentifier.TimingGroup, JSONPair>() {
                @Override
                public JSONPair apply(TimingIdentifier.TimingGroup group) {
                    return pair(group.id, group.name);
                }
            })), pair("handlers", handlers), pair("worlds", toObjectMapper(TimingHistory.worldMap.entrySet(),
                    new Function<Map.Entry<String, Integer>, JSONPair>() {
                        @Override
                        public JSONPair apply(Map.Entry<String, Integer> input) {
                            return pair(input.getValue(), input.getKey());
                        }
                    })),
            pair("tileentity", toObjectMapper(tileEntityTypeSet, new Function<Material, JSONPair>() {
                @Override
                public JSONPair apply(Material input) {
                    return pair(input.getId(), input.name());
                }
            })), pair("entity", toObjectMapper(entityTypeSet, new Function<EntityType, JSONPair>() {
                @Override
                public JSONPair apply(EntityType input) {
                    return pair(input.getTypeId(), input.name());
                }
            }))));

    // Information about loaded plugins

    parent.put("plugins",
            toObjectMapper(Bukkit.getPluginManager().getPlugins(), new Function<Plugin, JSONPair>() {
                @Override
                public JSONPair apply(Plugin plugin) {
                    return pair(plugin.getName(), createObject(
                            pair("version", plugin.getDescription().getVersion()),
                            pair("description",
                                    String.valueOf(plugin.getDescription().getDescription()).trim()),
                            pair("website", plugin.getDescription().getWebsite()),
                            pair("authors", StringUtils.join(plugin.getDescription().getAuthors(), ", "))));
                }
            }));

    // Information on the users Config

    parent.put("config", createObject(pair("spigot", mapAsJSON(Bukkit.spigot().getSpigotConfig(), null)),
            pair("bukkit", mapAsJSON(Bukkit.spigot().getBukkitConfig(), null))));

    new TimingsExport(sender, parent, history).start();
}

From source file:org.lnicholls.galleon.gui.Galleon.java

private static void printSystemProperties() {
    Properties properties = System.getProperties();
    Enumeration Enumeration = properties.propertyNames();
    for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
        String propertyName = (String) e.nextElement();
        log.info(propertyName + "=" + System.getProperty(propertyName));
    }//from  www .jav  a  2s.  c om
    Runtime runtime = Runtime.getRuntime();
    log.info("Max Memory: " + runtime.maxMemory());
    log.info("Total Memory: " + runtime.totalMemory());
    log.info("Free Memory: " + runtime.freeMemory());
}

From source file:com.aurel.track.admin.server.status.ServerStatusBL.java

private static void loadJavaRuntimeInfo(ServerStatusTO serverStatusTO) {
    Runtime rt = Runtime.getRuntime();
    long mbyte = 1024 * 1024;
    serverStatusTO.setJavaVersion(System.getProperty("java.version"));
    serverStatusTO.setJavaVendor(System.getProperty("java.vendor"));
    serverStatusTO.setJavaHome(System.getProperty("java.home"));
    serverStatusTO.setJavaVMVersion(System.getProperty("java.vm.version"));
    serverStatusTO.setJavaVMVendor(System.getProperty("java.vm.vendor"));
    serverStatusTO.setJavaVMName(System.getProperty("java.vm.name"));

    serverStatusTO.setJavaVMfreeMemory(rt.freeMemory() / mbyte);
    serverStatusTO.setJavaVMmaxMemory(rt.maxMemory() / mbyte);
    serverStatusTO.setJavaVMtotalMemory(rt.totalMemory() / mbyte);
    serverStatusTO//from www. ja  va 2 s  . c o  m
            .setJavaVMusedMemory(serverStatusTO.getJavaVMtotalMemory() - serverStatusTO.getJavaVMfreeMemory());
}

From source file:jp.terasoluna.fw.batch.util.BatchUtil.java

/**
 * Java ?????? ??????//ww w  .  j av  a  2 s  . c o  m
 * @return Java ?
 */
public static String getMemoryInfo() {
    DecimalFormat f1 = new DecimalFormat("#,###KB");
    DecimalFormat f2 = new DecimalFormat("##.#");

    Runtime rt = Runtime.getRuntime();
    long free = rt.freeMemory() / 1024;
    long total = rt.totalMemory() / 1024;
    long max = rt.maxMemory() / 1024;
    long used = total - free;
    double ratio = used * 100 / (double) total;

    StringBuilder sb = new StringBuilder();

    sb.append("Java memory info : ");
    sb.append("used=");
    sb.append(f1.format(used));
    sb.append(" (");
    sb.append(f2.format(ratio));
    sb.append("%), ");
    sb.append("total=");
    sb.append(f1.format(total));
    sb.append(", ");
    sb.append("max=");
    sb.append(f1.format(max));

    return sb.toString();
}

From source file:pcgen.util.Logging.java

/**
 * Generate the memory report string/*  w  ww.j  av  a2  s. c  o  m*/
 * @return the memory report string
 */
public static String memoryReportStr() {
    Runtime rt = Runtime.getRuntime();
    NumberFormat numFmt = NumberFormat.getNumberInstance();
    StringBuilder sb = new StringBuilder("Memory: ");
    sb.append(numFmt.format(rt.totalMemory() / 1024.0));
    sb.append("Kb total, ");
    sb.append(numFmt.format(rt.freeMemory() / 1024.0));
    sb.append("Kb free, ");
    sb.append(numFmt.format(rt.maxMemory() / 1024.0));
    sb.append("Kb max.");
    return sb.toString();
}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

public static Object getMemInfo(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    Scriptable memInfo = (Scriptable) MongoRuntime.call(new NewInstanceAction((MongoScope) thisObj, "Object"));

    Runtime runtime = Runtime.getRuntime();
    long freeMemory = runtime.freeMemory();
    long totalMemory = runtime.totalMemory();
    long maxMemory = runtime.maxMemory();

    ScriptableObject.putProperty(memInfo, "used", ((totalMemory - freeMemory) / 1024 / 1024));
    ScriptableObject.putProperty(memInfo, "total", (totalMemory / 1024 / 1024));
    ScriptableObject.putProperty(memInfo, "max", (maxMemory / 1024 / 1024));

    return memInfo;
}

From source file:com.redhat.developers.containers.MyController.java

@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/memory", produces = "text/plain")
public String memory() {
    System.out.println("Starting to allocate memory...");
    Runtime rt = Runtime.getRuntime();
    StringBuilder sb = new StringBuilder();
    long maxMemory = rt.maxMemory();
    long usedMemory = 0;
    while (((float) usedMemory / maxMemory) < 0.80) {
        sb.append(System.nanoTime() + sb.toString());
        usedMemory = rt.totalMemory();//from w w  w . j  a  v a  2 s.c o m
    }
    String msg = "Allocated more than 80% (" + humanReadableByteCount(usedMemory, false)
            + ") of the max allowed JVM memory size (" + humanReadableByteCount(maxMemory, false) + ")";
    System.out.println(msg);
    return msg;
}