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:xc.mst.repo.RepositoryDAO.java

private double getMemUsage() {
    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;
    double percentageUsed = ((double) usedMem) / maxMem;

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

    return percentageUsed;
}

From source file:org.unitime.timetable.onlinesectioning.server.AbstractServer.java

@Override
public long getMemUsage() {
    Runtime rt = Runtime.getRuntime();
    MemoryCounter mc = new MemoryCounter();
    DecimalFormat df = new DecimalFormat("#,##0.00");
    long total = 0; // mc.estimate(this);
    Map<String, String> info = new HashMap<String, String>();
    Class clazz = getClass();/*from  w  ww  .j  a va2 s.  c o m*/
    while (clazz != null) {
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (!Modifier.isStatic(fields[i].getModifiers())) {
                if (!fields[i].getType().isPrimitive()) {
                    fields[i].setAccessible(true);
                    try {
                        Object obj = fields[i].get(this);
                        if (obj != null) {
                            long est = estimate(mc, obj);
                            if (est > 1024)
                                info.put(clazz.getSimpleName() + "." + fields[i].getName(),
                                        df.format(est / 1024.0) + " kB"
                                                + (obj instanceof Map ? " (" + ((Map) obj).size() + " records)"
                                                        : obj instanceof Collection
                                                                ? "(" + ((Collection) obj).size() + " records)"
                                                                : ""));
                            total += est;
                        }
                    } catch (IllegalAccessException ex) {
                    } catch (ConcurrentModificationException ex) {
                    }
                }
            }
        }
        clazz = clazz.getSuperclass();
    }
    iLog.info("Total Allocated " + df.format(total / 1024.0) + " kB (of "
            + df.format((rt.totalMemory() - rt.freeMemory()) / 1048576.0) + " MB), details: "
            + ToolBox.dict2string(info, 2));
    return total;
}

From source file:cn.nukkit.Server.java

public void titleTick() {
    if (true || !Nukkit.ANSI) {
        return;//  ww w  .j a v a 2  s.  c  om
    }

    Runtime runtime = Runtime.getRuntime();
    double used = NukkitMath.round((double) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024, 2);
    double max = NukkitMath.round(((double) runtime.maxMemory()) / 1024 / 1024, 2);
    String usage = Math.round(used / max * 100) + "%";
    String title = (char) 0x1b + "]0;" + this.getName() + " " + this.getNukkitVersion() + " | Online "
            + this.players.size() + "/" + this.getMaxPlayers() + " | Memory " + usage;
    if (!Nukkit.shortTitle) {
        title += " | U " + NukkitMath.round((this.network.getUpload() / 1024 * 1000), 2) + " D "
                + NukkitMath.round((this.network.getDownload() / 1024 * 1000), 2) + " kB/s";
    }
    title += " | TPS " + this.getTicksPerSecond() + " | Load " + this.getTickUsage() + "%" + (char) 0x07;

    System.out.print(title);

    this.network.resetStatistics();
}

From source file:axiom.framework.core.Application.java

/**
 * Periodically called to log thread stats for this application
 *//*from   www.j  a v  a  2 s  . c  o  m*/
public void printThreadStats() {
    logEvent("Thread Stats for " + name + ": " + threadgroup.activeCount() + " active");

    Runtime rt = Runtime.getRuntime();
    long free = rt.freeMemory();
    long total = rt.totalMemory();

    logEvent("Free memory: " + (free / 1024) + " kB");
    logEvent("Total memory: " + (total / 1024) + " kB");
}

From source file:com.fanniemae.ezpie.LogManager.java

protected void initializeLog() {
    // Read JVM runtime settings
    Runtime runtime = Runtime.getRuntime();
    // Read the debug template
    String template = (_logFormat == LogFormat.HTML) ? readTemplateFile(_templatePath + "Debug.txt") : "";
    _startTime = System.currentTimeMillis();
    // Create debug file
    try (FileOutputStream fos = new FileOutputStream(_logFilename, false)) {
        fos.write(template.getBytes());/*w  w w . j  av  a  2s . c  o  m*/
        // Add machine information
        fos.write(String
                .format(_basicLine, "Environment Information", "Started",
                        new SimpleDateFormat("MMMM d, yyyy HH:mm:ss").format(new Date()), elapsedTime())
                .getBytes());
        fos.write(String.format(_basicLine, groupString(""), "User account name",
                System.getProperty("user.name"), elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "Machine Name",
                InetAddress.getLocalHost().getHostName(), elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Version", System.getProperty("java.version"),
                elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Architecture",
                System.getProperty("sun.arch.data.model") + " bit", elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Home", System.getProperty("java.home"),
                elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Vendor", System.getProperty("java.vendor"),
                elapsedTime()).getBytes());
        fos.write(String
                .format(_longTextLine, groupString(""), "JAVA Class Path",
                        System.getProperty("java.class.path").replace(";", ";" + _newLineTab), elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Maximum Memory",
                        String.format("%,d Megabytes", runtime.maxMemory() / 1048576), elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Total Allocated Memory",
                        String.format("%,d Megabytes reserved", runtime.totalMemory() / 1048576), elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Used Memory",
                        String.format("%,d Megabytes",
                                (runtime.totalMemory() - runtime.freeMemory()) / 1048576),
                        elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Free Memory",
                        String.format("%,d Megabytes", runtime.freeMemory() / 1048576), elapsedTime())
                .getBytes());
        fos.write(String.format(_basicLine, groupString(""), "Operating system name",
                System.getProperty("os.name"), elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "User working directory",
                System.getProperty("user.dir"), elapsedTime()).getBytes());
        fos.write(_footerByteArray);
        fos.close();
    } catch (IOException e) {
        throw new PieException(String.format("Error trying to create log file. %s", _logFilename), e);
    }
}

From source file:mondrian.olap.Util.java

public static String printMemory(String msg) {
    final Runtime rt = Runtime.getRuntime();
    final long freeMemory = rt.freeMemory();
    final long totalMemory = rt.totalMemory();
    final StringBuilder buf = new StringBuilder(64);

    buf.append("FREE_MEMORY:");
    if (msg != null) {
        buf.append(msg);//from   w  w  w  .  j  a  v  a 2s.c om
        buf.append(':');
    }
    buf.append(' ');
    buf.append(freeMemory / 1024);
    buf.append("kb ");

    long hundredths = (freeMemory * 10000) / totalMemory;

    buf.append(hundredths / 100);
    hundredths %= 100;
    if (hundredths >= 10) {
        buf.append('.');
    } else {
        buf.append(".0");
    }
    buf.append(hundredths);
    buf.append('%');

    return buf.toString();
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Get currently used memory//from  w w w  .ja  v a2s  . c om
 */
private long getUsedMemory(Runtime rt) {
    return (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024;
}

From source file:org.apache.accumulo.server.tabletserver.ScanRunState.java

private synchronized static void logGCInfo(AccumuloConfiguration conf) {
    List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans();
    Runtime rt = Runtime.getRuntime();

    StringBuilder sb = new StringBuilder("gc");

    boolean sawChange = false;

    long maxIncreaseInCollectionTime = 0;

    for (GarbageCollectorMXBean gcBean : gcmBeans) {
        Long prevTime = prevGcTime.get(gcBean.getName());
        long pt = 0;
        if (prevTime != null) {
            pt = prevTime;/*from  w w  w . j  a  va2s. c om*/
        }

        long time = gcBean.getCollectionTime();

        if (time - pt != 0) {
            sawChange = true;
        }

        long increaseInCollectionTime = time - pt;
        sb.append(String.format(" %s=%,.2f(+%,.2f) secs", gcBean.getName(), time / 1000.0,
                increaseInCollectionTime / 1000.0));
        maxIncreaseInCollectionTime = Math.max(increaseInCollectionTime, maxIncreaseInCollectionTime);
        prevGcTime.put(gcBean.getName(), time);
    }

    long mem = rt.freeMemory();
    if (maxIncreaseInCollectionTime == 0) {
        gcTimeIncreasedCount = 0;
    } else {
        gcTimeIncreasedCount++;
        if (gcTimeIncreasedCount > 3 && mem < rt.maxMemory() * 0.05) {
            log.warn("Running low on memory");
            gcTimeIncreasedCount = 0;
        }
    }

    if (mem > lastMemorySize) {
        sawChange = true;
    }

    String sign = "+";
    if (mem - lastMemorySize <= 0) {
        sign = "";
    }

    sb.append(String.format(" freemem=%,d(%s%,d) totalmem=%,d", mem, sign, (mem - lastMemorySize),
            rt.totalMemory()));

    if (sawChange) {
        log.debug(sb.toString());
    }

    final long keepAliveTimeout = conf.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT);
    if (maxIncreaseInCollectionTime > keepAliveTimeout) {
        Halt.halt("Garbage collection may be interfering with lock keep-alive.  Halting.", -1);
    }

    lastMemorySize = mem;
}

From source file:spade.reporter.Audit.java

private void printStats(boolean forcePrint) {
    if (reportingEnabled || forcePrint) {
        long currentTime = System.currentTimeMillis();
        if (((currentTime - lastReportedTime) >= reportEveryMs) || forcePrint) {
            Runtime runtime = Runtime.getRuntime();
            long usedMemoryMB = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024);
            int internalBufferSize = getBuffer().size();
            String statString = String.format("Internal buffer size: %d, JVM memory in use: %dMB",
                    internalBufferSize, usedMemoryMB);
            if (REFINE_NET) {
                String netfilterStat = String.format(
                        "Unmatched: " + "%d netfilter-syscall, " + "%d syscall-netfilter. " + "Matched: "
                                + "%d netfilter-syscall, " + "%d syscall-netfilter.",
                        networkAnnotationsFromNetfilter.size(), networkAnnotationsFromSyscalls.size(),
                        matchedNetfilterSyscall, matchedSyscallNetfilter);
                statString += ", " + netfilterStat;
            }//w  w w  .  j  a v  a2 s . c  o m
            logger.log(Level.INFO, statString);
            lastReportedTime = currentTime;
        }
    }
}

From source file:br.com.riselabs.cotonet.builder.commands.ExternalGitCommand.java

/**
 * OBS: this method returns {@code null} when calling '
 * {@code git reset --hard}'./*from  www .j a  va2  s . c o  m*/
 * 
 * @return
 * @throws IOException
 */
public List<ConflictChunk<CommandLineBlameResult>> call() throws BlameException {
    Runtime run = Runtime.getRuntime();
    Process pr = null;
    String cmd = null;
    String[] env = {};
    BufferedReader buf;
    List<ConflictChunk<CommandLineBlameResult>> conflicts = null;
    int exitCode;
    try {
        switch (type) {
        case RESET:
            cmd = "git reset --hard";
            pr = run.exec(cmd, env, file);
            break;

        case BLAME:
        default:
            cmd = "git blame -p --line-porcelain";
            env = new String[1];
            // we need this to disable the pager
            env[0] = "GIT_PAGER=cat";
            pr = run.exec(cmd + " " + file, env, file.getParentFile());
            // parse output
            buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            conflicts = new ArrayList<ConflictChunk<CommandLineBlameResult>>();

            final String CONFLICT_START = "<<<<<<<";
            final String CONFLICT_SEP = "=======";
            final String CONFLICT_END = ">>>>>>>";
            boolean addBlame = false;

            ConflictChunk<CommandLineBlameResult> conflict = new ConflictChunk<CommandLineBlameResult>(
                    file.getCanonicalPath());

            CommandLineBlameResult bResult;
            bResult = new CommandLineBlameResult(file.getCanonicalPath());
            Blame<CommandLineBlameResult> cBlame;
            cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult);
            List<String> block;
            while ((block = readPorcelainBlock(buf)) != null) {
                String commit = block.get(0).split(" ")[0];
                //   for (String line : block)
                //      System.out.println(line);

                Map<PKeys, String> data = getDataFromPorcelainBlock(block);

                String contentLine = data.get(PKeys.content);

                int n;
                if ((n = contentLine.trim().indexOf(" ")) == -1) {
                    // line without blank space
                    contentLine = contentLine.trim();
                } else {
                    contentLine = contentLine.trim().substring(0, n);
                }

                if (contentLine.equals(CONFLICT_START)) {
                    addBlame = true;
                    continue;
                } else if (contentLine.equals(CONFLICT_SEP)) {
                    addBlame = true;
                    cBlame.setRevision(scenario.getLeft());
                    conflict.setBase(scenario.getBase());
                    conflict.setLeft(cBlame);
                    bResult = new CommandLineBlameResult(file.getCanonicalPath());
                    cBlame = new Blame<CommandLineBlameResult>(scenario.getRight(), bResult);
                    continue;
                } else if (contentLine.equals(CONFLICT_END)) {
                    conflict.setRight(cBlame);
                    conflict.setLine(Integer.valueOf(data.get(PKeys.linenumber)));
                    conflicts.add(conflict);
                    addBlame = false;

                    bResult = new CommandLineBlameResult(file.getCanonicalPath());
                    cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult);

                    //@gustavo added this line
                    conflict = new ConflictChunk<CommandLineBlameResult>(file.getCanonicalPath());

                } else if (addBlame) {
                    // we are in one of the conflicting chunks
                    Integer linenumber = Integer.valueOf(data.get(PKeys.linenumber));
                    contentLine = data.get(PKeys.content);
                    String name = data.get(PKeys.authorname);
                    String email = data.get(PKeys.authormail);
                    DeveloperNode dev = new DeveloperNode(name, email);
                    conflict.setLine(linenumber);
                    bResult.addLineAuthor(linenumber, dev);
                    bResult.addLineContent(linenumber, contentLine);
                    bResult.addLineCommit(linenumber, commit);
                    continue;
                }
            }

            buf.close();
            break;
        }

        /*
         * already finished to execute the process. now, we should process
         * the error output.
         */
        buf = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

        String stdErr = IOUtils.toString(pr.getErrorStream(), StandardCharsets.UTF_8).trim();

        IOUtils.closeQuietly(pr.getInputStream());
        IOUtils.closeQuietly(pr.getErrorStream());
        IOUtils.closeQuietly(pr.getOutputStream());

        exitCode = pr.waitFor();

        buf.close();
        if (!stdErr.isEmpty()) {
            Logger.log(String.format("Execution of '%s' returned standard error output:%n%s", cmd, stdErr));
            throw new RuntimeException(
                    String.format("Error on external call with exit code %d", pr.exitValue()));
        }
    } catch (IOException io) {
        try {
            throw new BlameException(file.getCanonicalPath(), "IO Exception", io);
        } catch (IOException e) {
        }
    } catch (InterruptedException ie) {
        // waitFor() exception
        exitCode = 666;
        try {
            throw new BlameException(file.getCanonicalPath(), String.format(
                    "Interrupted while waiting for '%s' to finish. Error code: '%s'", cmd, exitCode), ie);
        } catch (IOException io) {
        }
    } catch (RuntimeException re) {
        try {
            throw new BlameException(file.getCanonicalPath(), "Runtime Exception", re);
        } catch (IOException e) {
        }
    } finally {
        run.freeMemory();
    }
    pr.destroyForcibly();
    return conflicts;
}