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:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is
 * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do
 * the actual work of the verb.//  w  ww . j  a v a2  s  .  c o m
 * 
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Fora gerao do cookie de sesso
    // (necessrio para balanceamento de carga pelo pound do Prodasen)
    request.getSession();

    HashMap attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    log.debug("attributes = " + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    HashMap serverVerbs = ServerVerb.getVerbs(properties);
    HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    request.setCharacterEncoding("UTF-8");

    Date then = null;
    if (monitor) {
        then = new Date();
    }
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        log.debug("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            log.debug(headerName + ": " + request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                /* && userAgent.indexOf("netscape/7") == -1 */) {
                    serverTransformer = transformer;
                }
            }
            String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer,
                    serverVerbs, extensionVerbs, extensionPath);

            Writer out = LexMLOAIHandler.getWriter(request, response);
            out.write(result);
            out.flush();
            IOUtils.closeQuietly(out);
        } catch (FileNotFoundException e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (Throwable e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        Runtime rt = Runtime.getRuntime();
        log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime())
                + "ms: " + reqUri.toString());
    }
}

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   ww w.  j  a  v a 2 s.co 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: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  ww w. j  a v a2 s  .co m
        header.append("\nHost        : ").append(InetAddress.getLocalHost());
    } catch (UnknownHostException e) {
        header.append("\nHost        : unknown");
    }
    header.append("\n");
    return header.toString();
}

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

/**
 * Store statistic data.//from w w  w  .j  a  v a2  s  .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);
    }
}

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 . j  a  v a  2s  . 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.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:org.apache.maven.doxia.linkcheck.DefaultLinkCheck.java

/**
 * Writes some memory data to the log (if debug enabled).
 */// www  .j a v a  2  s  .  c  om
private void displayMemoryConsumption() {
    if (LOG.isDebugEnabled()) {
        Runtime r = Runtime.getRuntime();
        LOG.debug("Memory: " + (r.totalMemory() - r.freeMemory()) / MEG + "M/" + r.totalMemory() / MEG + "M");
    }
}

From source file:ffx.Main.java

/**
 * Main does some window initializations.
 *
 * @param commandLineFile a {@link java.io.File} object.
 * @param argList a {@link java.util.List} object.
 *//* www  .  ja  v a 2 s  . c  om*/
public Main(File commandLineFile, List<String> argList) {
    super("Force Field X");
    // Start the clock.
    stopWatch.start();
    setVisible(false);

    // Create the MainPanel and MainMenu, then add them to the JFrame
    java.awt.Toolkit.getDefaultToolkit().setDynamicLayout(true);
    mainPanel = new MainPanel(this);
    logHandler.setMainPanel(mainPanel);
    add(mainPanel);
    mainPanel.initialize();
    setJMenuBar(mainPanel.getMainMenu());
    // Set the Title and Icon
    setTitle("Force Field X");
    URL iconURL = getClass().getClassLoader().getResource("ffx/ui/icons/icon64.png");
    ImageIcon icon = new ImageIcon(iconURL);
    setIconImage(icon.getImage());
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            if (mainPanel != null) {
                mainPanel.exit();
            }
            System.exit(0);
        }
    });
    // This is a hack to get GraphicsCanvis to initialize on some
    // platform/Java3D combinations.
    mainPanel.setPanel(MainPanel.KEYWORDS);
    setVisible(true);
    mainPanel.setPanel(MainPanel.GRAPHICS);
    // Mac OS X specific features that help Force Field X look native
    // on Macs. This needs to be done after the MainPanel is created.
    if (SystemUtils.IS_OS_MAC_OSX) {
        osxAdapter = new OSXAdapter(mainPanel);
    }

    // Finally, open the supplied file if necessary.
    if (commandLineFile != null && !commandLineFile.exists()) {
        /**
         * See if the commandLineFile is an embedded script.
         */
        String name = commandLineFile.getName();
        name = name.replace('.', '/');
        String pathName = "ffx/scripts/" + name;
        ClassLoader loader = getClass().getClassLoader();
        URL embeddedScript = loader.getResource(pathName + ".ffx");
        if (embeddedScript == null) {
            embeddedScript = loader.getResource(pathName + ".groovy");
        }
        if (embeddedScript != null) {
            try {
                commandLineFile = new File(FFXClassLoader.copyInputStreamToTmpFile(embeddedScript.openStream(),
                        commandLineFile.getName(), ".ffx"));
            } catch (Exception e) {
                logger.info(String.format(" The embedded script %s could not be extracted.", embeddedScript));
            }
        }
    }

    if (commandLineFile != null) {
        if (commandLineFile.exists()) {
            mainPanel.getModelingShell().setArgList(argList);
            mainPanel.open(commandLineFile, null);
        } else {
            logger.warning(format("%s was not found.", commandLineFile.toString()));
        }
    }

    if (logger.isLoggable(Level.FINE)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Start-up Time (msec): %s.", stopWatch.getTime()));
        Runtime runtime = Runtime.getRuntime();
        runtime.runFinalization();
        runtime.gc();
        long occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
        long KB = 1024;
        sb.append(format("\n In-Use Memory   (Kb): %d", occupiedMemory / KB));
        sb.append(format("\n Free Memory     (Kb): %d", runtime.freeMemory() / KB));
        sb.append(format("\n Total Memory    (Kb): %d", runtime.totalMemory() / KB));
        logger.fine(sb.toString());
    }
}

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

/**
 * Writes the attachment contained in the body part to a file.
 * //  w  w w.j  a  v a2s .  com
 * @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:spade.utility.BitcoinTools.java

public void writeBlocksToCSV(int startIndex, int endIndex) {
    // Block block, int lastBlockId
    int lastBlockId = -1;
    final BitcoinTools bitcoinTools = new BitcoinTools();

    String pattern = "#.##";
    DecimalFormat decimalFormat = new DecimalFormat(pattern);

    final ConcurrentHashMap<Integer, Block> blockMap = new ConcurrentHashMap<Integer, Block>();
    final AtomicInteger currentBlock = new AtomicInteger(startIndex);
    final int stopIndex = endIndex;
    final int totalThreads = Runtime.getRuntime().availableProcessors();

    class BlockFetcher implements Runnable {

        public void run() {

            while (true) {
                if (blockMap.size() > totalThreads * 5) { // max objects to hold in memory max 1 MB * totalThreads * factor
                    try {
                        Thread.sleep(100);
                        continue;
                    } catch (Exception exception) {
                    }/*  www. j a v a2  s . c  o  m*/
                }

                int blockToFetch = currentBlock.getAndIncrement();
                try {
                    blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch));
                } catch (JSONException exception) {
                    Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " has invalid json. Redownloading.",
                            exception);
                    try {
                        blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch));
                    } catch (JSONException ex) {
                        Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " couldn't be included in CSV.",
                                ex);
                    }
                }
                if (blockToFetch >= stopIndex) {
                    break;
                }
            }
        }
    }

    ArrayList<Thread> workers = new ArrayList<Thread>();
    for (int i = 0; i < totalThreads; i++) {
        Thread th = new Thread(new BlockFetcher());
        workers.add(th);
        th.start();
    }

    int percentageCompleted = 0;

    for (int i = startIndex; i < endIndex; i++) {

        try {

            Block block;
            while (!blockMap.containsKey(i)) {

            }
            block = blockMap.get(i);
            blockMap.remove(i);
            lastBlockId = writeBlockToCSV(block, lastBlockId);

            if ((((i - startIndex + 1) * 100) / (endIndex - startIndex)) > percentageCompleted) {
                Runtime rt = Runtime.getRuntime();
                long totalMemory = rt.totalMemory() / 1024 / 1024;
                long freeMemory = rt.freeMemory() / 1024 / 1024;
                long usedMemory = totalMemory - freeMemory;
                System.out.print("| Cores: " + rt.availableProcessors() + " | Threads: " + totalThreads
                        + " | Heap (MB) - total: " + totalMemory + ", %age free: "
                        + (freeMemory * 100) / totalMemory + " | At Block: " + (i - startIndex + 1) + " / "
                        + (endIndex - startIndex) + " | Percentage Completed: " + percentageCompleted
                        // + " |\r");
                        + " |\n");
            }

            percentageCompleted = ((i - startIndex + 1) * 100) / (endIndex - startIndex);

        } catch (IOException ex) {
            Bitcoin.log(Level.SEVERE, "Unexpected IOException. Stopping CSV creation.", ex);
            break;
        }
    }

    for (int i = 0; i < totalThreads; i++) {
        try {
            workers.get(i).interrupt();
            workers.get(i).join();
        } catch (InterruptedException exception) {
        }
    }

    System.out.println("\n\ndone with creating CSVes!");
}