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.spigotmc.timings.TimingsExport.java

/**
 * Builds an XML report of the timings to be uploaded for parsing.
 *
 * @param sender Who to report to/*from  ww  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:jp.terasoluna.fw.batch.util.BatchUtil.java

/**
 * Java ?????? ??????/*from  www .j  a va  2 s . c  om*/
 * @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: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  w w  w  . j ava2s .co  m
            .setJavaVMusedMemory(serverStatusTO.getJavaVMtotalMemory() - serverStatusTO.getJavaVMfreeMemory());
}

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:pcgen.util.Logging.java

/**
 * Generate the memory report string/*from   w  ww .  j av  a 2 s  .  c  om*/
 * @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.baasbox.metrics.BaasBoxMetric.java

private static void setGauges() {
    //memory gauges
    registry.register(name(GAUGE_MEMORY_MAX_ALLOCABLE), new CachedGauge<Long>(10, TimeUnit.MINUTES) {
        @Override/*w  w  w.ja v a2  s.  com*/
        public Long loadValue() {
            Runtime rt = Runtime.getRuntime();
            long maxMemory = rt.maxMemory();
            return maxMemory;
        }
    });

    registry.register(name(GAUGE_MEMORY_CURRENT_ALLOCATE), new Gauge<Long>() {
        @Override
        public Long getValue() {
            Runtime rt = Runtime.getRuntime();
            long totalMemory = rt.totalMemory();
            return totalMemory;
        }
    });

    registry.register(name(GAUGE_MEMORY_USED), new Gauge<Long>() {
        @Override
        public Long getValue() {
            Runtime rt = Runtime.getRuntime();
            long freeMemory = rt.freeMemory();
            long totalMemory = rt.totalMemory();
            return totalMemory - freeMemory;
        }
    });
    registry.register(name(GAUGE_FILESYSTEM_DATAFILE_SPACE_LEFT),
            new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public Long loadValue() {
                    return new File(BBConfiguration.getDBDir()).getFreeSpace();
                }
            });

    registry.register(name(GAUGE_FILESYSTEM_BACKUPDIR_SPACE_LEFT),
            new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public Long loadValue() {
                    return new File(BBConfiguration.getDBBackupDir()).getFreeSpace();
                }
            });

    registry.register(name(GAUGE_DB_DATA_SIZE), new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
        @Override
        public Long loadValue() {
            boolean opened = false;
            try {
                if (DbHelper.getConnection() == null || DbHelper.getConnection().isClosed()) {
                    DbHelper.open(BBConfiguration.getAPPCODE(), BBConfiguration.getBaasBoxAdminUsername(),
                            BBConfiguration.getBaasBoxAdminUsername());
                    opened = true;
                }
                return DbHelper.getConnection().getSize();
            } catch (InvalidAppCodeException e) {
                throw new RuntimeException(e);
            } finally {
                if (opened)
                    DbHelper.close(DbHelper.getConnection());
            }
        }
    });

    registry.register(name(GAUGE_DB_DATA_DIRECTORY_SIZE),
            new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public Long loadValue() {
                    return FileUtils.sizeOfDirectory(new File(BBConfiguration.getDBDir()));
                }
            });
    registry.register(name(GAUGE_DB_MAX_SIZE_THRESHOLD),
            new CachedGauge<BigInteger>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public BigInteger loadValue() {
                    return BBConfiguration.getDBSizeThreshold();
                }
            });

}

From source file:com.toughra.mlearnplayer.EXEStrMgr.java

/**
 * This is used to log error messages//w  w w .ja v  a 2s .  co m
 */
public static void lg(int errCode, String msg, Exception e) {
    if (e != null) {
        System.err.println(msg);
        e.printStackTrace();
        msg += "Exception: " + e.toString();
    }

    if (errCode > ERROR_LOG_THRESHOLD) {
        getInstance().l('D', errCode + ":" + msg, null, 0, 0, 0, 0, 0, null, 0, 0, null, null);
    }

    if (ERROR_LOG_THRESHOLD == 0) {
        //desperate debugging mode
        Runtime rt = Runtime.getRuntime();
        String memMsg = "Total Memory : " + rt.totalMemory() + " Free Memory " + rt.freeMemory();
        getInstance().l('D', memMsg, null, 0, 0, 0, 0, 0, null, 0, 0, null, null);

        try {
            getInstance().logOut.flush();
        } catch (IOException e2) {
            System.err.println("exception flushing log output");
        }
    }
}

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   ww  w . j av  a 2  s. c  o m
    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:edu.stanford.epadd.launcher.Splash.java

public static String getMemoryStats() {
    Runtime r = Runtime.getRuntime();
    System.gc();/*from w ww. j a  va  2 s  .  c om*/
    return r.freeMemory() / MB + " MB free, " + (r.totalMemory() / MB - r.freeMemory() / MB) + " MB used, "
            + r.maxMemory() / MB + " MB max, " + r.totalMemory() / MB + " MB total";
}

From source file:com.github.fedorchuck.webstore.web.controllers.SystemInfoController.java

@RequestMapping(value = "", method = GET)
public ModelAndView index() {
    ModelAndView model = new ModelAndView("sysinfo");

    final double mb = 1024 * 1024;
    Runtime runtime = Runtime.getRuntime();
    long usedRam = runtime.totalMemory() - runtime.freeMemory();

    Map<String, Double> mem = new TreeMap<>();
    mem.put("Used memory", usedRam / mb);
    mem.put("Total memory", runtime.totalMemory() / mb);
    mem.put("Free memory", runtime.freeMemory() / mb);

    model.getModel().put("mem", mem);

    //model.addObject("userActions", new UserActions());

    return model;
}