Example usage for java.lang Runtime totalMemory

List of usage examples for java.lang Runtime totalMemory

Introduction

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

Prototype

public native long totalMemory();

Source Link

Document

Returns the total amount of memory in the Java virtual machine.

Usage

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

@SuppressWarnings("unchecked")
private void startup() {
    try {/* w  ww . j  a va2 s .com*/
        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:org.opensextant.examples.BasicGeoTemporalProcessing.java

public void reportMemory() {
    Runtime R = Runtime.getRuntime();
    long usedMemory = R.totalMemory() - R.freeMemory();
    log.info("CURRENT MEM USAGE(K)=" + (int) (usedMemory / 1024));
}

From source file:org.loklak.api.admin.StatusService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization rights,
        JSONObjectWithDefault permissions) throws APIException {

    if (post.isLocalhostAccess() && OS.canExecUnix && post.get("upgrade", "").equals("true")) {
        Caretaker.upgrade(); // it's a hack to add this here, this may disappear anytime
    }//from  w  w  w.j a v a2s . c  o  m

    final String backend = DAO.getConfig("backend", "");
    final boolean backend_push = DAO.getConfig("backend.push.enabled", false);
    JSONObject backend_status = null;
    JSONObject backend_status_index_sizes = null;
    if (backend.length() > 0 && !backend_push)
        try {
            backend_status = StatusService.status(backend);
            backend_status_index_sizes = backend_status == null ? null
                    : (JSONObject) backend_status.get("index_sizes");
        } catch (IOException e) {
        }
    long backend_messages = backend_status_index_sizes == null ? 0
            : ((Number) backend_status_index_sizes.get("messages")).longValue();
    long backend_users = backend_status_index_sizes == null ? 0
            : ((Number) backend_status_index_sizes.get("users")).longValue();
    long local_messages = DAO.countLocalMessages();
    long local_users = DAO.countLocalUsers();

    post.setResponse(response, "application/javascript");

    // generate json
    Runtime runtime = Runtime.getRuntime();
    JSONObject json = new JSONObject(true);
    JSONObject system = new JSONObject(true);
    system.put("assigned_memory", runtime.maxMemory());
    system.put("used_memory", runtime.totalMemory() - runtime.freeMemory());
    system.put("available_memory", runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory());
    system.put("cores", runtime.availableProcessors());
    system.put("threads", Thread.activeCount());
    system.put("runtime", System.currentTimeMillis() - Caretaker.startupTime);
    system.put("time_to_restart", Caretaker.upgradeTime - System.currentTimeMillis());
    system.put("load_system_average", OS.getSystemLoadAverage());
    system.put("load_system_cpu", OS.getSystemCpuLoad());
    system.put("load_process_cpu", OS.getProcessCpuLoad());
    system.put("server_threads", LoklakServer.getServerThreads());
    system.put("server_uri", LoklakServer.getServerURI());

    JSONObject index = new JSONObject(true);
    long countLocalMinMessages = DAO.countLocalMessages(60000L);
    long countLocal10MMessages = DAO.countLocalMessages(600000L);
    long countLocalHourMessages = DAO.countLocalMessages(3600000L);
    long countLocalDayMessages = DAO.countLocalMessages(86400000L);
    long countLocalWeekMessages = DAO.countLocalMessages(604800000L);
    float mps1m = countLocalMinMessages / 60f;
    float mps10m = countLocal10MMessages / 600f;
    float mps1h = countLocalHourMessages / 3600f;
    float mps1d = countLocalDayMessages / 86400f;
    float mps1w = countLocalWeekMessages / 604800f;
    index.put("mps1m", mps1m);
    index.put("mps10m", mps10m);
    index.put("mps1h", mps1h);
    index.put("mps1d", mps1d);
    index.put("mps1w", mps1w);
    index.put("mps", (int) Math.max(mps1d, Math.max(mps1h, Math.max(mps10m, mps1m)))); // best of 1d, 1h and 10m
    JSONObject messages = new JSONObject(true);
    messages.put("size", local_messages + backend_messages);
    messages.put("size_local", local_messages);
    messages.put("size_local_minute", countLocalMinMessages);
    messages.put("size_local_10minutes", countLocal10MMessages);
    messages.put("size_local_hour", countLocalHourMessages);
    messages.put("size_local_day", countLocalDayMessages);
    messages.put("size_local_week", countLocalWeekMessages);
    messages.put("size_backend", backend_messages);
    messages.put("stats", DAO.messages.getStats());
    JSONObject queue = new JSONObject(true);
    queue.put("size", QueuedIndexing.getMessageQueueSize());
    queue.put("maxSize", QueuedIndexing.getMessageQueueMaxSize());
    queue.put("clients", QueuedIndexing.getMessageQueueClients());
    messages.put("queue", queue);
    JSONObject users = new JSONObject(true);
    users.put("size", local_users + backend_users);
    users.put("size_local", local_users);
    users.put("size_backend", backend_users);
    users.put("stats", DAO.users.getStats());
    JSONObject queries = new JSONObject(true);
    queries.put("size", DAO.countLocalQueries());
    queries.put("stats", DAO.queries.getStats());
    JSONObject accounts = new JSONObject(true);
    accounts.put("size", DAO.countLocalAccounts());
    JSONObject user = new JSONObject(true);
    user.put("size", DAO.user_dump.size());
    JSONObject followers = new JSONObject(true);
    followers.put("size", DAO.followers_dump.size());
    JSONObject following = new JSONObject(true);
    following.put("size", DAO.following_dump.size());
    index.put("messages", messages);
    index.put("users", users);
    index.put("queries", queries);
    index.put("accounts", accounts);
    index.put("user", user);
    index.put("followers", followers);
    index.put("following", following);
    if (DAO.getConfig("retrieval.queries.enabled", false)) {
        List<QueryEntry> queryList = DAO.SearchLocalQueries("", 1000, "retrieval_next", "date", SortOrder.ASC,
                null, new Date(), "retrieval_next");
        index.put("queries_pending", queryList.size());
    }

    JSONObject client_info = new JSONObject(true);
    client_info.put("RemoteHost", post.getClientHost());
    client_info.put("IsLocalhost", post.isLocalhostAccess() ? "true" : "false");

    JSONObject request_header = new JSONObject(true);
    Enumeration<String> he = post.getRequest().getHeaderNames();
    while (he.hasMoreElements()) {
        String h = he.nextElement();
        request_header.put(h, post.getRequest().getHeader(h));
    }
    client_info.put("request_header", request_header);

    json.put("system", system);
    json.put("index", index);
    json.put("client_info", client_info);

    return json;
}

From source file:weka.server.RootServlet.java

/**
 * Process a HTTP GET/*  w  w  w .ja  v  a  2 s.c  o  m*/
 * 
 * @param request the request
 * @param response the response
 * 
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO

    if (!request.getRequestURI().equals(CONTEXT_PATH)) {
        return;
    }

    response.setContentType("text/html;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);

    PrintWriter out = response.getWriter();

    try {
        out.println("<HTML>\n<HEAD>\n<TITLE>Weka server</TITLE>");
        out.println("<META http-equiv=\"Refresh\" content=\"30;url=" + CONTEXT_PATH + "\">");
        out.println("</HEAD>\n<BODY>");
        out.println("<H2> Weka Server (" + m_server.getHostname() + ":" + m_server.getPort() + ")</H2>");
        if (m_server.getMaster() != null) {
            out.println("Registered with master server: " + m_server.getMaster() + "<br>");
        }
        out.println("Number of execution slots: " + m_server.getNumExecutionSlots() + "<br>");
        out.println("Number of tasks executing: " + m_server.numRunningTasks() + "<br>");
        out.println("Number of tasks queued: " + m_server.numQueuedTasks() + "<br>");
        out.println("Load adjust factor: " + String.format("%.3f", m_server.getLoadAdjust()) + "<br>");
        out.println("Server load ((#executing + #queued) * loadFactor / #execution_slots): "
                + m_server.getServerLoad() + "<p>");
        System.gc();
        Runtime run = Runtime.getRuntime();
        long freeM = run.freeMemory();
        long totalM = run.totalMemory();
        long maxM = run.maxMemory();
        out.println("Memory (free/total/max) in bytes: " + String.format("%,d", freeM) + " / "
                + String.format("%,d", totalM) + " / " + String.format("%,d", maxM) + "<p>");

        if (m_server.getSlaves().size() > 0) {
            out.println("<H3>Slaves</H3>");
            out.println("<p>");

            out.println("<table border=\"1\">");
            out.print("<tr><th>");
            out.print("Host</th><th>Port</th><th>Status</th><th>Load</th></tr>\n");
            Set<String> slaves = m_server.getSlaves();
            for (String slave : slaves) {
                String[] parts = slave.split(":");
                out.print("<tr>");
                out.print("<td><a href=\"http://" + parts[0] + ":" + parts[1] + "\">" + parts[0]
                        + "</a></td><td>" + parts[1] + "</td>");
                double load = getSlaveLoad(m_server, slave);
                String okString = (load < 0) ? "connection error" : "OK";

                out.print("<td>" + okString + "</td><td>" + load + "</td></tr>\n");
            }
            out.print("</table><p>");
        }

        out.println("<p>");

        out.println("<H3>Tasks</H3>");

        out.println("<table border=\"1\">");
        out.print("<tr><th>");
        out.print("Task name</th><th>ID</th><th>Server</th><th>Last execution</th><th>Next execution</th>"
                + "<th>Status</th><th>Purge</th></tr>\n");
        List<WekaTaskMap.WekaTaskEntry> taskList = m_taskMap.getTaskList();
        for (WekaTaskMap.WekaTaskEntry entry : taskList) {
            String name = entry.getName();
            String id = entry.getID();
            NamedTask task = m_taskMap.getTask(entry);
            TaskStatusInfo tsi = task.getTaskStatus();
            // Date lastExecuted = m_taskMap.getExecutionTime(entry);
            Date lastExecuted = entry.getLastExecution();
            Date nextExecution = null;
            if (task instanceof Scheduled) {
                nextExecution = ((Scheduled) task).getSchedule().nextExecution(lastExecuted);
            }

            out.print("<tr>");
            out.print("<td><a href=\"" + GetTaskStatusServlet.CONTEXT_PATH + "?name="
                    + URLEncoder.encode(entry.toString(), "UTF-8") + "\">" + name + "</a></td>");
            out.print("<td>" + id + "</td>");
            String server = entry.getServer();
            if (server.equals(m_server.getHostname() + ":" + m_server.getPort())) {
                server = "local";
            }
            out.print("<td>");
            if (!server.equals("local")) {
                out.print("<a href=\"http://" + server + "\">" + server + "</a></td>");
            } else {
                out.print("" + server + "</td>");
            }

            String formattedLastDate = " - ";
            String formattedNextDate = " - ";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            if (lastExecuted != null) {
                formattedLastDate = sdf.format(lastExecuted);
            }
            out.print("<td>" + formattedLastDate + "</td>");

            if (nextExecution != null) {
                formattedNextDate = sdf.format(nextExecution);
            }
            out.print("<td>" + formattedNextDate + "</td>");

            out.print("<td>" + GetTaskStatusServlet.taskStatusInfoToString(tsi) + "</td>");

            if (tsi.getExecutionStatus() != TaskStatusInfo.PROCESSING) {
                out.print("<td><a href=\"" + PurgeTaskServlet.CONTEXT_PATH + "?name="
                        + URLEncoder.encode(entry.toString(), "UTF-8") + "\">Remove</a></td>");
            } else {
                out.print("<td> -- </td>");
            }
            out.print("</tr>\n");
        }
        out.print("</table><p>");

        out.println("</BODY>\n</HTML>");
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
            out = null;
        }
    }
}

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  .ja  va 2 s  .  c  om
        header.append("\nHost        : ").append(InetAddress.getLocalHost());
    } catch (UnknownHostException e) {
        header.append("\nHost        : unknown");
    }
    header.append("\n");
    return header.toString();
}

From source file:at.beris.virtualfile.shell.Shell.java

private void displayStatistics() {
    Runtime runtime = Runtime.getRuntime();
    System.out.println("** Heap utilization statistics [KB] **");
    System.out/*from ww w. ja v  a2 s.  co  m*/
            .println(String.format("Used Memory: %,d", (runtime.totalMemory() - runtime.freeMemory()) / 1024));
    System.out.println(String.format("Free Memory: %,d", runtime.freeMemory() / 1024));
    System.out.println(String.format("Total Memory: %,d", runtime.totalMemory() / 1024));
    System.out.println(String.format("Max Memory: %,d", runtime.maxMemory() / 1024));
}

From source file:org.sentilo.samples.controller.SamplesController.java

@RequestMapping(value = { "/", "/home" })
public String runSamples(final Model model) {

    // All this data must be created in the Catalog Application before start this
    // sample execution. At least the application identity token id and the provider id must be
    // declared in system twice
    String restClientIdentityKey = samplesProperties.getProperty("rest.client.identityKey");
    String providerId = samplesProperties.getProperty("rest.client.provider");

    // For this example we have created a generic component with a status sensor that accepts text
    // type observations, only for test purpose
    String componentId = samplesProperties.getProperty("rest.client.component");
    String sensorId = samplesProperties.getProperty("rest.client.sensor");

    logger.info("Starting samples execution...");

    String observationsValue = null;
    String errorMessage = null;//from   w  w  w. j a  v a 2  s .c  o m

    try {
        // Get some system data from runtime
        Runtime runtime = Runtime.getRuntime();
        NumberFormat format = NumberFormat.getInstance();
        StringBuilder sb = new StringBuilder();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();

        sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
        sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
        sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
        sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024)
                + "<br/>");

        // In this case, we're getting CPU status in text mode
        observationsValue = sb.toString();

        logger.info("Observations values: " + observationsValue);

        // Create the sample sensor, only if it doesn't exists in the catalog
        createSensorIfNotExists(restClientIdentityKey, providerId, componentId, sensorId);

        // Publish observations to the sample sensor
        sendObservations(restClientIdentityKey, providerId, componentId, sensorId, observationsValue);
    } catch (Exception e) {
        logger.error("Error publishing sensor observations: " + e.getMessage(), e);
        errorMessage = e.getMessage();
    }

    logger.info("Samples execution ended!");

    model.addAttribute("restClientIdentityKey", restClientIdentityKey);
    model.addAttribute("providerId", providerId);
    model.addAttribute("componentId", componentId);
    model.addAttribute("sensorId", sensorId);
    model.addAttribute("observations", observationsValue);

    ObjectMapper mapper = new ObjectMapper();

    try {
        if (errorMessage != null && errorMessage.length() > 0) {
            Object json = mapper.readValue(errorMessage, Object.class);
            model.addAttribute("errorMsg", mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
        } else {
            model.addAttribute("successMsg", "Observations sended successfully");
        }
    } catch (Exception e) {
        logger.error("Error parsing JSON: {}", e.getMessage(), e);
        errorMessage += (errorMessage.length() > 0) ? "<br/>" : "" + e.getMessage();
        model.addAttribute("errorMsg", errorMessage);
    }

    return VIEW_SAMPLES_RESPONSE;
}

From source file:org.apache.maven.index.cli.NexusIndexerCli.java

private void printStats(final long startTimeInMillis) {
    long t = System.currentTimeMillis() - startTimeInMillis;

    long s = t / 1000L;
    if (t > 60 * 1000) {
        long m = t / 1000L / 60L;

        System.err.printf("Total time:   %d min %d sec\n", m, s - (m * 60));
    } else {//from   w  w  w .  j  ava2s  . c  o  m
        System.err.printf("Total time:   %d sec\n", s);
    }

    Runtime r = Runtime.getRuntime();

    System.err.printf("Final memory: %dM/%dM\n", //
            (r.totalMemory() - r.freeMemory()) / MB, r.totalMemory() / MB);
}

From source file:org.LexGrid.LexBIG.distributed.test.testUtility.PerformanceTest.java

public void printMemoryStatistics() {

    int mb = 1024 * 1024;

    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    System.out.println("##### Heap utilization statistics [MB] #####");

    //Print used memory
    System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

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

    //Print total available memory
    System.out.println("Total Memory:" + runtime.totalMemory() / mb);

    //Print Maximum available memory
    System.out.println("Max Memory:" + runtime.maxMemory() / mb);
}

From source file:de.xwic.appkit.core.trace.impl.TraceDataManager.java

/**
 * Store statistic data./*from w  w  w  .  jav  a 2s  . c  o  m*/
 * 
 * @param sts
 * @param history
 */
protected void populateSystemTraceStatistic(ISystemTraceStatistic sts, long interval,
        List<ITraceContext> history) {

    Runtime rt = Runtime.getRuntime();
    long used = (rt.totalMemory() - rt.freeMemory()) >> 20; //show memory in MB

    sts.setMemoryUsed(used);
    sts.setHost(hostName);
    sts.setInstanceId(instanceId);

    if (!history.isEmpty()) {

        long max = System.currentTimeMillis() - (interval + 10); // make an "overlap of 10ms"
        long hisStart = history.get(0).getStartTime();
        long from = hisStart < max ? max : hisStart;
        long to = history.get(history.size() - 1).getStartTime();

        sts.setFromDate(new Date(from));
        if (to >= from) {
            sts.setToDate(new Date(to));
        } else {
            sts.setToDate(null);
        }

        int count = 0;
        long total = 0;

        int daoOps = 0;
        long daoDuration = 0;

        List<TraceStats> traceStats = new ArrayList<ISystemTraceStatistic.TraceStats>();

        for (String catName : systemTraceLogCategories) {
            TraceStats ts = new TraceStats();
            ts.setName(catName);
            traceStats.add(ts);
        }

        LinkedHashMap<Integer, TraceStats> traceIntervals = new LinkedHashMap<Integer, ISystemTraceStatistic.TraceStats>(
                traceIntervalBuckets.length);
        for (int x : traceIntervalBuckets) {
            TraceStats ts = new TraceStats();
            ts.setName("Duration-" + x);
            traceIntervals.put(x, ts);
        }

        for (ITraceContext tx : history) {
            if (tx.getStartTime() >= from) { // skip older entries
                count++;
                total += tx.getDuration();
                putInIntervalBucket(tx, traceIntervals);
                ITraceCategory daoCategory = tx.getTraceCategory(DAO.TRACE_CAT);
                if (daoCategory != null) {
                    daoOps += daoCategory.getCount();
                    daoDuration += daoCategory.getTotalDuration();
                }

                for (TraceStats ts : traceStats) {
                    countCat(ts, tx);
                }
            }
        }

        sts.setResponseCount(count);
        sts.setTotalResponseTime(total);
        sts.setAverageResponseTime(count != 0 ? total / count : 0d);

        sts.setTotalDAODuration(daoDuration);
        sts.setTotalDAOops(daoOps);

        traceStats.addAll(traceIntervals.values());
        sts.setTraceStats(traceStats);
    }
}