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: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  a  2 s  . 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:com.concentricsky.android.khanacademy.util.ThumbnailManager.java

private LruCache<Thumbnail, Bitmap> prepareCache() {
    // Total available heap size. This changes based on manifest android:largeHeap="true". (Fire HD, transformer both go from 48MB to 256MB)
    Runtime rt = Runtime.getRuntime();
    long maxMemory = rt.maxMemory();
    Log.v(LOG_TAG, "maxMemory:" + Long.toString(maxMemory));

    // Want to use at most about 1/2 of available memory for thumbs.
    // In SAT Math category (116 videos), with a heap size of 48MB, this setting
    // allows 109 thumbs to be cached resulting in total heap usage around 34MB.
    long usableMemory = maxMemory / 2;

    return new LruCache<Thumbnail, Bitmap>((int) usableMemory) {
        @Override/*from ww  w.j a v a  2 s  .c o m*/
        protected int sizeOf(Thumbnail key, Bitmap value) {
            return value.getByteCount();
        }

        @Override
        protected void entryRemoved(boolean evicted, Thumbnail key, Bitmap oldValue, Bitmap newValue) {
            if (oldValue != newValue) {
                oldValue.recycle();
            }
        }
    };

}

From source file:models.monitor.MonitorProvider.java

public PerformUsage getJVMMemoryUsage() {
    int mb = 1024 * 1024;
    Runtime rt = Runtime.getRuntime();
    PerformUsage usage = new PerformUsage();
    usage.totalMemory = (double) rt.totalMemory() / mb;
    usage.freeMemory = (double) rt.freeMemory() / mb;
    usage.usedMemory = (double) rt.totalMemory() / mb - rt.freeMemory() / mb;
    usage.maxMemory = (double) rt.maxMemory() / mb;
    usage.memoryUsagePercent = usage.usedMemory / usage.totalMemory * 100.0;

    //            new BigDecimal().setScale(2) .divide(new BigDecimal(usage.totalMemory).setScale(2), RoundingMode.DOWN)
    //                                                  .setScale(2)
    //                                                  .multiply(new BigDecimal(100)).intValue();

    // update current
    currentJvmPerformUsage = usage;//from  w  ww .  j  av a  2s.com
    return usage;
}

From source file:org.ambraproject.action.debug.DebugInfoAction.java

@Override
public String execute() throws Exception {
    if (!checkAccess()) {
        return ERROR;
    }//from  w w  w.  ja v  a 2 s  .c  o m
    timestamp = new Date(System.currentTimeMillis());
    Runtime rt = Runtime.getRuntime();
    jvmFreeMemory = (double) rt.freeMemory() / (1024.0 * 1024.0);
    jvmTotalMemory = (double) rt.totalMemory() / (1024.0 * 1024.0);
    jvmMaxMemory = (double) rt.maxMemory() / (1024.0 * 1024.0);
    HttpServletRequest req = ServletActionContext.getRequest();
    tomcatVersion = ServletActionContext.getServletContext().getServerInfo();
    sessionCount = SessionCounter.getSessionCount();
    host = req.getLocalName();
    hostIp = req.getLocalAddr();
    buildInfo = generateBuildInfo();

    // The easiest way I found to get the URL and username for the DB.
    // It's not that easy and involves opening a connection...
    Context initialContext = new InitialContext();
    Context context = (Context) initialContext.lookup("java:comp/env");
    DataSource ds = (DataSource) context.lookup("jdbc/AmbraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        DatabaseMetaData metadata = conn.getMetaData();
        dbUrl = metadata.getURL();
        dbUser = metadata.getUserName();
    } finally {
        conn.close();
    }

    Configuration config = ConfigurationStore.getInstance().getConfiguration();
    FileStoreService filestoreService = (FileStoreService) context.lookup("ambra/FileStore");
    filestore = filestoreService.toString();
    solrUrl = (String) config.getProperty("ambra.services.search.server.url");
    configuration = dumpConfig(config);
    cmdLine = IOUtils.toString(new FileInputStream("/proc/self/cmdline"));

    return SUCCESS;
}

From source file:ome.services.util.JvmSettingsCheck.java

public JvmSettingsCheck() {
    final String fmt = "%s = %6s";
    final Runtime rt = Runtime.getRuntime();
    final int mb = 1024 * 1024;

    StringBuilder version = new StringBuilder();
    for (String key : new String[] { "java.version", "os.name", "os.arch", "os.version" }) {
        if (version.length() != 0) {
            version.append("; ");
        }/*from   w w  w. j  a  v  a2s  . com*/
        version.append(System.getProperty(key));
    }

    log.info("Java version: " + version);
    log.info(String.format(fmt, "Max Memory (MB):  ", (rt.maxMemory() / mb)));
    log.info(String.format(fmt, "OS Memory (MB):   ", (getPhysicalMemory() / mb)));
    log.info(String.format(fmt, "Processors:       ", rt.availableProcessors()));
}

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 ww w  .jav  a  2 s .com

    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.alfresco.repo.content.transform.TikaPoweredContentTransformer.java

private String calculateMemoryAndTimeUsage(ContentReader reader, long startTime) {
    long endTime = System.currentTimeMillis();
    Runtime runtime = Runtime.getRuntime();
    long totalMemory = runtime.totalMemory();
    return String.format(USAGE_PATTERN, this.getClass().getName(), reader,
            (totalMemory - runtime.freeMemory()) / MEGABYTES, totalMemory / MEGABYTES,
            runtime.maxMemory() / MEGABYTES, (endTime - startTime));
}

From source file:org.openmrs.module.emrmonitor.metric.JavaRuntimeMetricProducer.java

/**
 * @return a list of produced metrics//from  ww w.j  av  a2  s . c  o m
 */
@Override
public Map<String, String> produceMetrics() {

    Map<String, String> metrics = new LinkedHashMap<String, String>();

    // Memory
    Runtime runtime = Runtime.getRuntime();
    metrics.put("memory.total", FormatUtil.formatBytes(runtime.totalMemory()));
    metrics.put("memory.total.bytes", Long.toString(runtime.totalMemory()));
    metrics.put("memory.free", FormatUtil.formatBytes(runtime.freeMemory()));
    metrics.put("memory.free.bytes", Long.toString(runtime.freeMemory()));
    metrics.put("memory.maximum", FormatUtil.formatBytes(runtime.maxMemory()));
    metrics.put("memory.maximum.bytes", Long.toString(runtime.maxMemory()));

    // Date/time
    Calendar cal = Calendar.getInstance();
    metrics.put("datetime.display", DateFormat.getDateTimeInstance().format(cal.getTime()));
    metrics.put("datetime.date", DateFormatUtils.ISO_DATE_FORMAT.format(cal));
    metrics.put("datetime.time", DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(cal));
    metrics.put("datetime.timezone", cal.getTimeZone().getDisplayName());

    // Java
    Properties sp = System.getProperties();
    metrics.put("version", sp.getProperty("java.version"));
    metrics.put("vendor", sp.getProperty("java.vendor"));
    metrics.put("jvmVersion", sp.getProperty("java.vm.version"));
    metrics.put("jvmVendor", sp.getProperty("java.vm.vendor"));
    metrics.put("runtimeName", sp.getProperty("java.runtime.name"));
    metrics.put("runtimeVersion", sp.getProperty("java.runtime.version"));
    metrics.put("user.name", sp.getProperty("user.name"));
    metrics.put("user.language", sp.getProperty("user.language"));
    metrics.put("user.timezone", sp.getProperty("user.timezone"));
    metrics.put("user.directory", sp.getProperty("user.dir"));
    metrics.put("encoding", sp.getProperty("sun.jnu.encoding"));
    metrics.put("tempDirectory", sp.getProperty("java.io.tmpdir"));

    return metrics;
}

From source file:org.uva.itast.TestOMRProcessor.java

@Test
public void testProcessMultiPagePDFmultiDefinitions() {
    try {/*from w  w w  . j a v a 2s . co m*/
        //        if (false) 
        //             return;

        URL url = getClass().getClassLoader().getResource("56605.pdf");
        File testPath = new File(url.toURI());

        // use a single, common, template definition
        prepareConfig(testPath);
        File dir = testPath.getParentFile();
        Vector<PageImage> errores;

        if (logger.isInfoEnabled()) {
            logger.info("Test with definitions in a zip."); //$NON-NLS-1$
        }

        processor.getTemplates().clear();
        File zipDefinitions = new File(dir, "form_test.zip");
        processor.loadTemplateCollection(zipDefinitions.getAbsolutePath());

        detectErrors(testPath);
        // deteccin de errores
        // use a collection of templates from a directory
        if (logger.isInfoEnabled()) {
            logger.info("Test with definitions in a directory."); //$NON-NLS-1$
        }
        processor.getTemplates().clear();
        processor.loadTemplateCollection(dir.getAbsolutePath());

        detectErrors(testPath);

    } catch (Exception e) {
        fail("Can't configure test case." + e);
    } catch (OutOfMemoryError err) {
        Runtime runtime = Runtime.getRuntime();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long maxMemory = runtime.maxMemory();
        String errorMsg = "testProcessMultiPagePDFmultiDefinitions(): Out of Memory.\n" + "Total:" + totalMemory
                + "\n" + "Max:" + maxMemory + "\n" + "Free:" + freeMemory;
        logger.fatal(errorMsg, err); //$NON-NLS-1$
        fail(errorMsg);
    }
}

From source file:weka.server.RootServlet.java

/**
 * Process a HTTP GET/*from w ww .j av  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;
        }
    }
}