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.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:org.apache.hadoop.metrics.jvm.JvmMetrics.java

private void doMemoryUpdates() {
    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage memNonHeap = memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();
    Runtime runtime = Runtime.getRuntime();

    metrics.setMetric("memNonHeapUsedM", memNonHeap.getUsed() / M);
    metrics.setMetric("memNonHeapCommittedM", memNonHeap.getCommitted() / M);
    metrics.setMetric("memHeapUsedM", memHeap.getUsed() / M);
    metrics.setMetric("memHeapCommittedM", memHeap.getCommitted() / M);
    metrics.setMetric("maxMemoryM", runtime.maxMemory() / M);
}

From source file:com.betfair.tornjak.monitor.FreeMemoryMonitor.java

/**
 * Answers the amount of free memory in this runtime environment, as a percentage.
 *//*from   ww w  .ja v  a 2  s. c om*/
@Override
@ManagedAttribute()
public int getFreeMemoryPercentage() {
    Runtime runtime = Runtime.getRuntime();
    // 'totalMemory' is how much heap we have *currently*
    // - this may increase up to 'maxMemory' (and can decrease)
    long totalMemory = runtime.totalMemory();
    // 'freeMemory' is 'totalMemory' - allocated)
    long freeMemory = runtime.freeMemory();
    // Work out how much we have used
    long allocatedMemory = totalMemory - freeMemory;
    // 'maxMemory' is equivalent to the JVM option '-Xmx'
    long maxMemory = runtime.maxMemory();
    // Work out the percentage used
    return (int) (100 - (allocatedMemory * 100 / maxMemory));
}

From source file:org.wso2.carbon.mediation.statistics.monitor.EsbStatisticsConsumer.java

private void updateMemoryView(MemoryStatView view) {
    Runtime runtime = Runtime.getRuntime();

    view.setTotalMemory(runtime.totalMemory() / MEGA);
    view.setFreeMemory(runtime.freeMemory() / MEGA);
    view.setUsedMemory((runtime.totalMemory() - runtime.freeMemory()) / MEGA);
    view.setMaxMemory(runtime.maxMemory() / MEGA);
}

From source file:com.ettrema.zsync.IntegrationTests.java

/**
 * Creates the zsync File for servercopy, and saves it to a File with name fileName
 * @param fileName The name of the file in which to save the zsync data
 * @param blocksize The block size to use in MetaFileMaker
 * @return The created zsync File/*from w ww .  j a v a2  s.  c o  m*/
 * @throws FileNotFoundException
 */
private File createMetaFile(String fileName, int blocksize, File serverFile) throws FileNotFoundException {
    System.out.println("---------------- createMetaFile -------------------");

    System.gc();
    Runtime rt = Runtime.getRuntime();
    startUsed = rt.totalMemory() - rt.freeMemory();

    MetaFileMaker mkr = new MetaFileMaker();
    File zsfile = mkr.make(null, blocksize, serverFile);
    System.gc();
    System.out.println("Memory stats: " + formatBytes(rt.maxMemory()) + " - " + formatBytes(rt.totalMemory())
            + " - " + formatBytes(rt.freeMemory()));
    long endUsed = (rt.totalMemory() - rt.freeMemory());
    System.out.println("Start used memory: " + formatBytes(startUsed) + " end used memory: "
            + formatBytes(endUsed) + " - delta: " + formatBytes(endUsed - startUsed));

    File dest = new File(filepath + fileName);
    if (dest.exists()) {
        if (!dest.delete()) {
            throw new RuntimeException("Failed to delete previous meta file: " + dest.getAbsolutePath());
        }
    }
    System.out.println("rename meta file to: " + dest.getAbsolutePath());
    if (!zsfile.renameTo(dest)) {
        throw new RuntimeException("Failed to rename to: " + dest.getAbsolutePath());
    }
    System.out.println("Created meta file of size: " + formatBytes(dest.length())
            + " from source file of size: " + formatBytes(serverFile.length()));
    System.out.println("");
    return dest;
}

From source file:qa.qcri.nadeef.test.core.SQLTableTest.java

public void testSize() throws InterruptedException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    SQLTable table = new SQLTable("TB_test60m", connectionFactory);
    table.get(0);//from w  ww.  j a va 2  s  . co m

    long elapsedTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    int mb = 1024 * 1024;

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

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

    long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / mb;
    System.out.println("Used Memory:" + usedMemory);
    System.out.println("Free Memory:" + runtime.freeMemory() / mb);
    System.out.println("Total Memory:" + runtime.totalMemory() / mb);
    System.out.println("Max Memory:" + runtime.maxMemory() / mb);
    System.out.println("Load time: " + elapsedTime + " ms.");

    // memory usage should be less than 700 mb.
    Assert.assertTrue(usedMemory < 700);

    // load time should be less than 18000 ms
    Assert.assertTrue(elapsedTime < 18000);
}

From source file:com.atlassian.jira.startup.JiraSystemInfo.java

/**
 * This only gets the most basic environment information to avoid bring up the JIRA world before the raw database
 * checks are done.//w  ww  . j av  a  2s .c  om
 * <p/>
 * It MUST BE CAREFUL not to access an JIRA code that will bring up the world
 *
 * @param context - a ServletContext that the app is running in.  This may be nulll
 */
public void obtainBasicInfo(final ServletContext context) {
    final SystemInfoUtils systemInfoUtils = new SystemInfoUtilsImpl();
    final ReleaseInfo releaseInfo = ReleaseInfo.getReleaseInfo(ReleaseInfo.class);

    logMsg.outputHeader("Environment");

    logMsg.outputProperty("JIRA Build", buildUtilsInfo.getBuildInformation());
    logMsg.outputProperty("Build Date", String.valueOf(buildUtilsInfo.getCurrentBuildDate()));
    logMsg.outputProperty("JIRA Installation Type", releaseInfo.getInfo());

    if (context != null) {
        logMsg.outputProperty("Application Server", context.getServerInfo() + " - Servlet API "
                + context.getMajorVersion() + "." + context.getMinorVersion());
    }
    logMsg.outputProperty("Java Version", jiraSystemProperties.getProperty("java.version", STRANGELY_UNKNOWN)
            + " - " + jiraSystemProperties.getProperty("java.vendor", STRANGELY_UNKNOWN));
    logMsg.outputProperty("Current Working Directory",
            jiraSystemProperties.getProperty("user.dir", STRANGELY_UNKNOWN));

    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGABYTE;
    final long totalMemory = rt.totalMemory() / MEGABYTE;
    final long freeMemory = rt.freeMemory() / MEGABYTE;
    final long usedMemory = totalMemory - freeMemory;

    logMsg.outputProperty("Maximum Allowable Memory", maxMemory + "MB");
    logMsg.outputProperty("Total Memory", totalMemory + "MB");
    logMsg.outputProperty("Free Memory", freeMemory + "MB");
    logMsg.outputProperty("Used Memory", usedMemory + "MB");

    for (final MemoryInformation memory : systemInfoUtils.getMemoryPoolInformation()) {
        logMsg.outputProperty("Memory Pool: " + memory.getName(), memory.toString());
    }
    logMsg.outputProperty("JVM Input Arguments", systemInfoUtils.getJvmInputArguments());

    // do we have any patches
    Set<AppliedPatchInfo> appliedPatches = AppliedPatches.getAppliedPatches();
    if (appliedPatches.size() > 0) {
        logMsg.outputHeader("Applied Patches");
        for (AppliedPatchInfo appliedPatch : appliedPatches) {
            logMsg.outputProperty(appliedPatch.getIssueKey(), appliedPatch.getDescription());
        }
    }
    logMsg.outputProperty("Java Compatibility Information", "JIRA version = " + buildUtilsInfo.getVersion()
            + ", Java Version = " + jiraSystemProperties.getProperty("java.version", STRANGELY_UNKNOWN));
}

From source file:org.klco.email2html.OutputWriter.java

/**
 * Writes the attachment contained in the body part to a file.
 * //from  w  w  w . j  a  v a 2s . c om
 * @param containingMessage
 *            the message this body part is contained within
 * @param part
 *            the part containing the attachment
 * @return the file that was created/written to
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws MessagingException
 *             the messaging exception
 */
public boolean writeAttachment(EmailMessage containingMessage, Part part)
        throws IOException, MessagingException {
    log.trace("writeAttachment");

    File attachmentFolder;
    File attachmentFile;
    InputStream in = null;
    OutputStream out = null;
    try {

        attachmentFolder = new File(outputDir.getAbsolutePath() + File.separator + config.getImagesSubDir()
                + File.separator + FILE_DATE_FORMAT.format(containingMessage.getSentDate()));
        if (!attachmentFolder.exists()) {
            log.debug("Creating attachment folder");
            attachmentFolder.mkdirs();
        }

        attachmentFile = new File(attachmentFolder, part.getFileName());
        log.debug("Writing attachment file: {}", attachmentFile.getAbsolutePath());
        if (!attachmentFile.exists()) {
            attachmentFile.createNewFile();
        }

        in = new BufferedInputStream(part.getInputStream());
        out = new BufferedOutputStream(new FileOutputStream(attachmentFile));

        log.debug("Downloading attachment");
        CRC32 checksum = new CRC32();
        for (int b = in.read(); b != -1; b = in.read()) {
            checksum.update(b);
            out.write(b);
        }

        if (this.excludeDuplicates) {
            log.debug("Computing checksum");
            long value = checksum.getValue();
            if (this.attachmentChecksums.contains(value)) {
                log.info("Skipping duplicate attachment: {}", part.getFileName());
                attachmentFile.delete();
                return false;
            } else {
                attachmentChecksums.add(value);
            }
        }

        log.debug("Attachement saved");
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }

    if (part.getContentType().toLowerCase().startsWith("image")) {
        log.debug("Creating renditions");
        String contentType = part.getContentType().substring(0, part.getContentType().indexOf(";"));
        log.debug("Creating renditions of type: " + contentType);

        for (Rendition rendition : renditions) {
            File renditionFile = new File(attachmentFolder, rendition.getName() + "-" + part.getFileName());
            try {
                if (!renditionFile.exists()) {
                    renditionFile.createNewFile();
                }
                log.debug("Creating rendition file: {}", renditionFile.getAbsolutePath());
                createRendition(attachmentFile, renditionFile, rendition);
                log.debug("Rendition created");
            } catch (OutOfMemoryError oome) {
                Runtime rt = Runtime.getRuntime();
                rt.gc();
                log.warn("Ran out of memory creating rendition: " + rendition, oome);

                log.warn("Free Memory: {}", rt.freeMemory());
                log.warn("Max Memory: {}", rt.maxMemory());
                log.warn("Total Memory: {}", rt.totalMemory());

                String[] command = null;
                if (rendition.getFill()) {
                    command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize",
                            (rendition.getHeight() * 2) + "x", "-resize",
                            "'x" + (rendition.getHeight() * 2) + "<'", "-resize", "50%", "-gravity", "center",
                            "-crop", rendition.getHeight() + "x" + rendition.getWidth() + "+0+0", "+repage",
                            renditionFile.getAbsolutePath() };
                } else {
                    command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize",
                            rendition.getHeight() + "x" + rendition.getWidth(),
                            renditionFile.getAbsolutePath() };

                }
                log.debug("Trying to resize with ImageMagick: " + StringUtils.join(command, " "));

                rt.exec(command);
            } catch (Exception t) {
                log.warn("Exception creating rendition: " + rendition, t);
            }
        }
    }
    return true;
}

From source file:org.apache.hadoop.hdfs.server.namenode.Namenode2AgentServiceImpl.java

@Override
public Map<String, Long> getJVMHeap() {
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    Map<String, Long> result = new HashMap<>();
    result.put("Max Memory", maxMemory);
    result.put("Total Memory", totalMemory);
    result.put("Free Memory", freeMemory);
    result.put("Used Memory", usedMemory);
    return result;
}

From source file:org.mrgeo.services.wms.WmsGenerator.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from  w  w w  . j  a  v a  2s . c  om*/
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final long start = System.currentTimeMillis();
    try {
        log.debug("Semaphores available: {}", semaphore.availablePermits());
        semaphore.acquire();
        log.debug("Semaphore acquired.  Semaphores available: {}", semaphore.availablePermits());

        ServletUtils.printRequestURL(request);
        ServletUtils.printRequestAttributes(request);
        ServletUtils.printRequestParams(request);

        final String cache = ServletUtils.getParamValue(request, "cache");
        if (!StringUtils.isEmpty(cache) && cache.toLowerCase().equals("off")) {
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
        } else {
            response.setHeader("Cache-Control", "max-age=3600");
            response.setHeader("Pragma", "");
            response.setDateHeader("Expires", 3600);
        }

        String requestParam = ServletUtils.getParamValue(request, "request");
        if (requestParam == null || requestParam.isEmpty()) {
            requestParam = "GetCapabilities";
        }
        requestParam = requestParam.toLowerCase();

        String serviceParam = ServletUtils.getParamValue(request, "service");
        if (serviceParam == null || serviceParam.isEmpty()) {
            serviceParam = "wms";
        }
        if (!serviceParam.toLowerCase().equals("wms")) {
            throw new Exception(
                    "Invalid service type was requested. (only WMS is supported '" + serviceParam + "')");
        }

        if (requestParam.equals("getmap") || requestParam.equals("getmosaic")
                || requestParam.equals("gettile")) {
            if (!requestParam.equals("gettile")) {
                ServletUtils.validateParam(request, "layers", "string");
            } else {
                ServletUtils.validateParam(request, "layer", "string");
            }
            ServletUtils.validateParam(request, "format", "string");
            final String cs = ServletUtils.getParamValue(request, "crs");
            if (!StringUtils.isEmpty(cs)) {
                if (!cs.toUpperCase().equals("CRS:84")) {
                    throw new Exception("InvalidCRS: Invalid coordinate system \"" + cs
                            + "\".  Only coordinate system CRS:84 is supported.");
                }
            }

            OpImageRegistrar.registerMrGeoOps();
        }

        // TODO: Need to construct provider properties from the WebRequest using
        // a new security layer and pass those properties to MapAlgebraJob.
        Properties providerProperties = SecurityUtils.getProviderProperties();
        if (requestParam.equals("getcapabilities")) {
            getCapabilities(request, response, providerProperties);
        } else if (requestParam.equals("getmap")) {
            getMap(request, response, providerProperties);
        } else if (requestParam.equals("getmosaic")) {
            getMosaic(request, response, providerProperties);
        } else if (requestParam.equals("gettile")) {
            getTile(request, response, providerProperties);
        } else if (requestParam.equals("describetiles")) {
            describeTiles(request, response, providerProperties);
        } else {
            throw new Exception("Invalid request type made.");
        }
    } catch (final Exception e) {
        e.printStackTrace();
        try {
            response.setContentType("text/xml");
            writeError(e, response);
        }
        // we already started writing out to HTTP, instead return an error.
        catch (final Exception exception) {
            log.warn("Exception writing error: {}", exception);
            throw new IOException("Exception while writing XML exception (ah, the irony). "
                    + "Original Exception is below." + exception.getLocalizedMessage(), e);
        }
    } finally {
        semaphore.release();

        if (log.isDebugEnabled()) {
            log.debug("Semaphore released.  Semaphores available: {}", semaphore.availablePermits());
            log.debug("WMS request time: {}ms", (System.currentTimeMillis() - start));
            // this can be resource intensive.
            System.gc();
            final Runtime rt = Runtime.getRuntime();
            log.debug(String.format("WMS request memory: %.1fMB / %.1fMB\n",
                    (rt.totalMemory() - rt.freeMemory()) / 1e6, rt.maxMemory() / 1e6));
        }
    }
}