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.ktunaxa.referral.server.service.SystemService.java

@Scheduled(fixedRate = 2000)
public void showLog() {
    int mb = 1024 * 1024;

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

    log.info("##### Heap utilization statistics [MB] #####");

    // Print used memory
    log.info("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

    // Print free memory
    log.info("Free Memory:" + runtime.freeMemory() / mb);

    // Print total available memory
    log.info("Total Memory:" + runtime.totalMemory() / mb);

    // Print Maximum available memory
    log.info("Max Memory:" + runtime.maxMemory() / mb);
}

From source file:it.damore.tomee.envmonitor.services.EnvMonitorService.java

@GET
@Path("monitor")
@Produces({ MediaType.APPLICATION_JSON })
public EnvironmentConfig getEnvConfig() throws IllegalAccessException, InvocationTargetException {
    logger.info("received a request...");

    int mb = 1024 * 1024;
    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();

    EnvironmentConfig b = new EnvironmentConfig();
    b.setMaxMemory(runtime.maxMemory() / mb);
    b.setFreeMemory(runtime.freeMemory() / mb);
    b.setTotalMemory(runtime.totalMemory() / mb);
    b.setSystemProperties(System.getProperties());

    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    LocalRuntimeMXBean myRuntimeMXBean = new LocalRuntimeMXBean();
    BeanUtils.copyProperties(myRuntimeMXBean, runtimeMXBean);
    b.setRuntimeMXBean(myRuntimeMXBean);

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    LocalMemoryMXBean myMemoryMXBean = new LocalMemoryMXBean();
    myMemoryMXBean.setHeapMemoryUsage(memoryMXBean.getHeapMemoryUsage());
    myMemoryMXBean.setNonHeapMemoryUsage(memoryMXBean.getNonHeapMemoryUsage());
    myMemoryMXBean.setObjectPendingFinalizationCount(memoryMXBean.getObjectPendingFinalizationCount());
    b.setMemoryMXBean(myMemoryMXBean);//from ww  w  .java2  s.c o  m

    OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    LocalOperatingSystemMXBean myOperatingSystemMXBean = new LocalOperatingSystemMXBean();
    BeanUtils.copyProperties(myOperatingSystemMXBean, operatingSystemMXBean);
    b.setOperatingSystemMXBean(myOperatingSystemMXBean);

    return b;
}

From source file:org.gedantic.web.servlet.FileUploadHandler.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug(">doPost");

    // process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {//from  ww  w.  ja v a  2s.com
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            long length = 0;
            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    if (!item.getName().toLowerCase().endsWith(".ged")
                            && !item.getName().toLowerCase().endsWith(".gedcom")) {
                        LOG.info("Upload file " + item.getName() + " doesn't end in .ged or .gedcom");
                        throw new RuntimeException(
                                "Upload file " + item.getName() + " doesn't end in .ged or .gedcom");
                    }
                    if (item.getSize() > MAX_MB * 1024 * 1024) {
                        LOG.info("Upload file " + item.getName() + " exceeds " + MAX_MB + "MB limit - was "
                                + item.getSize());
                        throw new RuntimeException("Upload file " + item.getName() + " exceeds " + MAX_MB
                                + "MB limit - was " + item.getSize());
                    }
                    String name = new File(item.getName()).getName();
                    String fullPathAndName = UPLOAD_DIRECTORY + File.separator + name;
                    File file = new File(fullPathAndName);
                    item.write(file);
                    length = file.length();
                    LOG.info("Wrote " + fullPathAndName + " (" + length + " bytes)");

                    new ParserAndLoader(request, response, file).parseAndLoadIntoSession();
                }
            }
        } catch (RuntimeException ex) {
            LOG.error("Unable to upload file: " + ex.getMessage());
            response.setStatus(403);
        } catch (Exception ex) {
            LOG.error("Unable to upload file: ", ex);
            response.setStatus(403);
        }
    }

    Runtime rt = Runtime.getRuntime();
    long maxMemory = rt.maxMemory();
    long freeMemory = rt.freeMemory();
    LOG.info("fileUploaded - freeMemory:" + Double.toString(freeMemory / (1024 * 1024)) + " maxMemory:"
            + Double.toString(maxMemory / (1024 * 1024)));

    LOG.debug("<doPost");
}

From source file:org.sakaiproject.content.impl.serialize.impl.test.ProfileSerializerTest.java

/**
 * Test method for/*from  w  w w.ja  v  a2 s  .c  o  m*/
 * {@link org.sakaiproject.content.impl.serialize.impl.Type1BaseContentCollectionSerializer#parse(org.sakaiproject.entity.api.serialize.SerializableEntity, java.lang.String)}.
 * 
 * @throws Exception
 */
@Test
public final void testParse() throws Exception {
    Type1BaseContentCollectionSerializer t1 = new Type1BaseContentCollectionSerializer();
    t1.setTimeService(new MockTimeService());
    MockSerializableCollectionAcccess sc = new MockSerializableCollectionAcccess();
    byte[] serialized = null;
    Runtime r = Runtime.getRuntime();
    r.gc();
    Thread.sleep(2000);
    {
        long start = System.currentTimeMillis();
        long ms = r.freeMemory();
        for (int i = 0; i < 16000; i++) {
            serialized = t1.serialize(sc);
        }
        long me = r.freeMemory();
        long m = ms - me;
        long end = System.currentTimeMillis();
        long t = (end - start);
        log.info("Write 16000 Entities took " + t + "ms ");
        log.info("Write 16000 Entities took " + (t * 1000) / 16000 + " us/entity ");
        log.info("Write 16000 Entities took " + m + " bytes overhead ");
        log.info("Write 16000 Entities took " + (m / 16000) + " bytes/entity overhead ");
    }
    r.gc();
    Thread.sleep(2000);
    {
        long start = System.currentTimeMillis();
        long ms = r.freeMemory();
        for (int i = 0; i < 16000; i++) {
            t1.parse(sc, serialized);
        }
        long me = r.freeMemory();
        long m = ms - me;
        long end = System.currentTimeMillis();
        long t = (end - start);
        log.info("Read 16000 Entities took " + t + "ms ");
        log.info("Read 16000 Entities took " + (t * 1000) / 16000 + " us/entity ");
        log.info("Read 16000 Entities took " + m + " bytes overhead ");
        log.info("Read 16000 Entities took " + (m / 16000) + " bytes/entity overhead ");
    }
    sc.check();
}

From source file:org.polymap.core.model2.test.SimpleModelTest.java

protected void logHeap() {
    System.gc();//  ww w . j  av  a2  s . c om
    Runtime rt = Runtime.getRuntime();
    log.info("HEAP: free/total: " + FileUtils.byteCountToDisplaySize(rt.freeMemory()) + " / "
            + FileUtils.byteCountToDisplaySize(rt.totalMemory()));
}

From source file:io.cloudslang.worker.management.monitor.WorkerMonitorsImpl.java

@Override
public synchronized Map<WorkerMonitorInfoEnum, Serializable> getMonitorInfo() {
    try {// ww  w  . j  ava2 s .c  o  m
        Map<WorkerMonitorInfoEnum, Serializable> monitorInfo = Maps.newHashMap();

        Runtime runtime = Runtime.getRuntime();
        monitorInfo.put(WorkerMonitorInfoEnum.TOTAL_MEMORY, runtime.totalMemory());
        monitorInfo.put(WorkerMonitorInfoEnum.FREE_MEMORY, runtime.freeMemory());
        monitorInfo.put(WorkerMonitorInfoEnum.MAX_MEMORY, runtime.maxMemory());

        monitorInfo.put(WorkerMonitorInfoEnum.WORKER_ID, workerManager.getWorkerUuid());

        monitorInfo.put(WorkerMonitorInfoEnum.EXECUTION_THREADS_AMOUNT,
                workerManager.getExecutionThreadsCount());

        monitorInfo.put(WorkerMonitorInfoEnum.OUTBUFFER_CAPACITY, outBuffer.getCapacity());

        monitorInfo.put(WorkerMonitorInfoEnum.INBUFFER_CAPACITY, inBuffer.getCapacity());

        for (WorkerMonitor monitor : monitors) {
            monitor.captureMonitorInfo(monitorInfo);
        }

        monitorInfo.put(WorkerMonitorInfoEnum.MONITOR_START_TIME, monitorStartTime);
        monitorInfo.put(WorkerMonitorInfoEnum.MONITOR_END_TIME, System.currentTimeMillis());

        return monitorInfo;
    } finally {
        resetMonitor();
    }
}

From source file:org.apache.pulsar.common.stats.JvmMetrics.java

public List<Metrics> generate() {

    Metrics m = createMetrics();//from   w ww  .ja v a2s. c o  m

    Runtime r = Runtime.getRuntime();

    m.put("jvm_heap_used", r.totalMemory() - r.freeMemory());
    m.put("jvm_max_memory", r.maxMemory());
    m.put("jvm_total_memory", r.totalMemory());

    m.put("jvm_direct_memory_used", getJvmDirectMemoryUsed());
    m.put("jvm_max_direct_memory", PlatformDependent.maxDirectMemory());
    m.put("jvm_thread_cnt", getThreadCount());

    this.gcLogger.logMetrics(m);

    long totalAllocated = 0;
    long totalUsed = 0;

    for (PoolArenaMetric arena : PooledByteBufAllocator.DEFAULT.directArenas()) {
        for (PoolChunkListMetric list : arena.chunkLists()) {
            for (PoolChunkMetric chunk : list) {
                int size = chunk.chunkSize();
                int used = size - chunk.freeBytes();

                totalAllocated += size;
                totalUsed += used;
            }
        }
    }

    m.put(this.componentName + "_default_pool_allocated", totalAllocated);
    m.put(this.componentName + "_default_pool_used", totalUsed);

    return Lists.newArrayList(m);
}

From source file:com.kyne.webby.bukkit.RTKModuleSocket.java

private void getInfos(final Map<String, Object> responseParams) {
    final List<WebbyPlayer> playerList = new ArrayList<WebbyPlayer>();
    for (final Player player : Bukkit.getOnlinePlayers()) {
        playerList.add(new WebbyPlayer(player.getName(), player.isOp()));
    }//ww w . j  av  a2  s. c  om
    final Runtime runtime = Runtime.getRuntime();
    final long freeMemory = runtime.freeMemory();
    final long totalMemory = runtime.totalMemory();
    final long maxMemory = runtime.maxMemory();
    final int mb = 1024 * 1024;

    final ServerInfos serverInfos = new ServerInfos(Bukkit.getVersion(), Bukkit.getMaxPlayers(),
            playerList.size(), playerList, freeMemory / mb, totalMemory / mb, maxMemory / mb);
    responseParams.put("DATA", serverInfos);
}

From source file:org.ngrinder.operation.cotroller.StatisticsController.java

/**
 * Get current jvm stat/*from  w  w  w  .  java 2s  .c om*/
 * 
 * @return map for jvm used/free/total/max
 */
private Map<String, Long> getJVMStat() {
    Runtime runtime = Runtime.getRuntime();

    Map<String, Long> stat = new HashMap<String, Long>();
    stat.put("used", runtime.totalMemory() - runtime.freeMemory());
    stat.put("free", runtime.freeMemory());
    stat.put("total", runtime.totalMemory());
    stat.put("max", runtime.maxMemory());

    return stat;
}

From source file:org.gedantic.web.servlet.AnalyzerServlet.java

/**
 * Servlet for handling all analysis requests
 * // w  w  w. j  a  v  a  2s  .  c om
 * @param req
 *            the http request
 * @param resp
 *            the http response
 * @throws ServletException
 *             if there is a code-related problemDescription
 * @throws IOException
 *             if there is a network or storage-related problemDescription
 */
private void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    Gedcom g = (Gedcom) session.getAttribute(Constants.GEDCOM);
    IAnalyzer a = null;

    String analyzerId = req.getParameter("analyzerId");
    if (analyzerId != null) {
        a = AnalyzerList.getInstance().getAnalyzers().get(analyzerId);
        req.setAttribute(Constants.ANALYSIS_ID, a.getId());
        req.setAttribute(Constants.ANALYSIS_NAME, a.getName());
        req.setAttribute(Constants.ANALYSIS_DESCRIPTION, a.getDescription());
    }

    if (g == null) {
        LOG.info("Redirecting from " + req.getRequestURI()
                + " to upload page because there is no gedcom in session");
        req.setAttribute(Constants.ALERT_MESSAGE, "Please upload a GEDCOM to analyze");
        req.setAttribute(Constants.ALERT_MESSAGE_TYPE, "alert alert-warning");
        req.getRequestDispatcher(Constants.URL_UPLOAD_PAGE).forward(req, resp);
        return;
    }

    if (a == null) {
        LOG.info("Redirecting from " + req.getRequestURI()
                + " to upload page because the analysis ID could not be interpreted");
        req.setAttribute(Constants.ALERT_MESSAGE, "Unknown analysis type");
        req.setAttribute(Constants.ALERT_MESSAGE_TYPE, "alert alert-danger");
        req.getRequestDispatcher(Constants.URL_UPLOAD_PAGE).forward(req, resp);
        return;

    }

    Runtime rt = Runtime.getRuntime();
    long maxMemory = rt.maxMemory();
    long freeMemory = rt.freeMemory();
    LOG.info("before analysis " + a.getId() + " - freeMemory:" + Double.toString(freeMemory / (1024 * 1024))
            + " maxMemory:" + Double.toString(maxMemory / (1024 * 1024)));

    List<AnalysisResult> results = a.analyze(g);
    Collections.sort(results, new AnalysisResultComparator());

    maxMemory = rt.maxMemory();
    freeMemory = rt.freeMemory();
    LOG.info("after analysis " + a.getId() + " - freeMemory:" + Double.toString(freeMemory / (1024 * 1024))
            + " maxMemory:" + Double.toString(maxMemory / (1024 * 1024)));

    if ("true".equals(req.getParameter("excel"))) {
        @SuppressWarnings("resource")
        Workbook wb = new WorkbookCreator(a, results).create();

        resp.setContentType("application/vnd.ms-excel");
        resp.setHeader("Content-disposition",
                "attachment; filename=" + StringEscapeUtils.escapeHtml(a.getName() + ".xlsx"));

        wb.write(resp.getOutputStream());
        resp.getOutputStream().flush();

    } else {
        req.setAttribute(Constants.RESULTS, results);
        req.getRequestDispatcher("results.tiles").forward(req, resp);
    }
}