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:com.jaspersoft.studio.community.utils.CommunityAPIUtils.java

/**
 * @return software and hardware info.//w  ww. j  ava2  s  . c  o m
 */
public static String getHardwareSoftwareInfo() {
    BrandingInfo currBranding = JaspersoftStudioPlugin.getInstance().getBrandingInformation();
    String c = ""; //$NON-NLS-1$
    c += "Product Name: " + currBranding.getProductName() + CR; //$NON-NLS-1$
    c += "Product Version: " + currBranding.getProductVersion() + CR; //$NON-NLS-1$
    c += "Installation Path: " + getInstallationPath(currBranding.getProductMainBundleID()) + CR; //$NON-NLS-1$
    c += "Eclipse Version: " + PlatformInfo.getEclipseVersion().toString() //$NON-NLS-1$
            + CR;
    c += "Eclipse Build Name: " + PlatformInfo.getEclipseBuildName() + CR; //$NON-NLS-1$
    c += "Eclipse Build ID: " + PlatformInfo.getEclipseBuildId() + CR; //$NON-NLS-1$
    c += "IDE Name: " + PlatformInfo.getIDEName() + CR; //$NON-NLS-1$
    c += "IDE Version: " + PlatformInfo.getIDEVersionString() + CR; //$NON-NLS-1$
    c += "IDE NL: " + PlatformInfo.getIDENL() + CR; //$NON-NLS-1$
    c += "Eclipse Commands: " //$NON-NLS-1$
            + StringUtils.replaceChars(getSystemProperty("eclipse.commands"), "\n\r", " ") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            + CR;
    c += "Eclipse VM: " + getSystemProperty("eclipse.vm") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "Eclipse VM Args: " + getSystemProperty("eclipse.vmargs") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "OS Name: " + getSystemProperty("os.name") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "OS Arch: " + getSystemProperty("os.arch") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "OS Version: " + getSystemProperty("os.version") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    String linuxDescription = getLinuxDescription();
    if (!StringUtils.isEmpty(linuxDescription)) {
        c += "Linux Description: " + linuxDescription + CR; //$NON-NLS-1$
    }
    String m_mozillaResult = tryCreateMozilla();
    if (!StringUtils.isEmpty(m_mozillaResult)) {
        c += "Browser Creation Result: " + m_mozillaResult + CR; //$NON-NLS-1$
    }
    Runtime runtime = Runtime.getRuntime();
    c += "Available Processors: " + runtime.availableProcessors() + CR; //$NON-NLS-1$
    c += "Memory Max: " + runtime.maxMemory() + CR; //$NON-NLS-1$
    c += "Memory Total: " + runtime.totalMemory() + CR; //$NON-NLS-1$
    c += "Memory Free: " + runtime.freeMemory() + CR; //$NON-NLS-1$
    c += "Java Vendor: " + getSystemProperty("java.vendor") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "Java Version: " + getSystemProperty("java.version") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    c += "Java Library Path: " + getSystemProperty("java.library.path") + CR; //$NON-NLS-1$ //$NON-NLS-2$
    return c;
}

From source file:org.b3log.latke.servlet.HTTPRequestDispatcher.java

/**
 * Dispatches with the specified context.
 * //from  w  w w  .  ja v a2 s . c  o  m
 * @param context the specified specified context
 * @throws ServletException servlet exception
 * @throws IOException io exception 
 */
public static void dispatch(final HTTPRequestContext context) throws ServletException, IOException {
    final HttpServletRequest request = context.getRequest();

    String requestURI = (String) request.getAttribute(Keys.HttpRequest.REQUEST_URI);

    if (Strings.isEmptyOrNull(requestURI)) {
        requestURI = request.getRequestURI();
    }

    String method = (String) request.getAttribute(Keys.HttpRequest.REQUEST_METHOD);

    if (Strings.isEmptyOrNull(method)) {
        method = request.getMethod();
    }

    LOGGER.log(Level.FINER, "Request[requestURI={0}, method={1}]", new Object[] { requestURI, method });

    try {
        final Object processorMethodRet = RequestProcessors.invoke(requestURI, Latkes.getContextPath(), method,
                context);
    } catch (final Exception e) {
        final String exceptionTypeName = e.getClass().getName();

        LOGGER.log(Level.FINER,
                "Occured error while processing request[requestURI={0}, method={1}, exceptionTypeName={2}, errorMsg={3}]",
                new Object[] { requestURI, method, exceptionTypeName, e.getMessage() });
        if ("com.google.apphosting.api.ApiProxy$OverQuotaException".equals(exceptionTypeName)) {
            PageCaches.removeAll();

            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            return;
        }

        throw new ServletException(e);
    } catch (final Error e) {
        final Runtime runtime = Runtime.getRuntime();

        LOGGER.log(Level.FINER, "Memory status[total={0}, max={1}, free={2}]",
                new Object[] { runtime.totalMemory(), runtime.maxMemory(), runtime.freeMemory() });

        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        throw e;
    }

    // XXX: processor method ret?

    final HttpServletResponse response = context.getResponse();

    if (response.isCommitted()) { // Sends rdirect or send error
        final PrintWriter writer = response.getWriter();

        writer.flush();
        writer.close();

        return;
    }

    AbstractHTTPResponseRenderer renderer = context.getRenderer();

    if (null == renderer) {
        renderer = new HTTP404Renderer();
    }

    renderer.render(context);
}

From source file:eu.delving.sip.Application.java

private static void memoryNotConfigured() {
    String os = System.getProperty("os.name");
    Runtime rt = Runtime.getRuntime();
    int totalMemory = (int) (rt.totalMemory() / 1024 / 1024);
    StringBuilder out = new StringBuilder();
    String JAR_NAME = "SIP-Creator-2014-XX-XX.jar";
    if (os.startsWith("Windows")) {
        out.append(":: SIP-Creator Startup Batch file for Windows (more memory than ").append(totalMemory)
                .append("Mb)\n");
        out.append("java -jar -Xms1024m -Xmx1024m ").append(JAR_NAME);
    } else if (os.startsWith("Mac")) {
        out.append("# SIP-Creator Startup Script for Mac OSX (more memory than ").append(totalMemory)
                .append("Mb)\n");
        out.append("java -jar -Xms1024m -Xmx1024m ").append(JAR_NAME);
    } else {/*from w  w w  .j  a  va  2 s. c  om*/
        System.out.println("Unrecognized OS: " + os);
    }
    String script = out.toString();
    final JDialog dialog = new JDialog(null, "Memory Not Configured Yet!",
            Dialog.ModalityType.APPLICATION_MODAL);
    JTextArea scriptArea = new JTextArea(3, 40);
    scriptArea.setText(script);
    scriptArea.setSelectionStart(0);
    scriptArea.setSelectionEnd(script.length());
    JPanel scriptPanel = new JPanel(new BorderLayout());
    scriptPanel.setBorder(BorderFactory.createTitledBorder("Script File"));
    scriptPanel.add(scriptArea, BorderLayout.CENTER);
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
    JButton ok = new JButton("OK, Continue anyway");
    ok.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.setVisible(false);
            EventQueue.invokeLater(LAUNCH);
        }
    });
    buttonPanel.add(ok);
    JPanel centralPanel = new JPanel(new GridLayout(0, 1));
    centralPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 15, 25));
    centralPanel.add(
            new JLabel("<html><b>The SIP-Creator started directly can have too little default memory allocated."
                    + "<br>It should be started with the following script:</b>"));
    centralPanel.add(scriptPanel);
    centralPanel.add(new JLabel(
            "<html><b>Please copy the above text into a batch or script file and execute that instead.</b>"));
    dialog.getContentPane().add(centralPanel, BorderLayout.CENTER);
    dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    dialog.pack();
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - dialog.getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - dialog.getHeight()) / 2);
    dialog.setLocation(x, y);
    dialog.setVisible(true);
}

From source file:io.bitsquare.common.util.Utilities.java

public static void printSystemLoad() {
    Runtime runtime = Runtime.getRuntime();
    long free = runtime.freeMemory() / 1024 / 1024;
    long total = runtime.totalMemory() / 1024 / 1024;
    long used = total - free;
    log.info("System load (no. threads/used memory (MB)): " + Thread.activeCount() + "/" + used);
}

From source file:edu.illinois.cs.cogcomp.lbjava.classify.TestReal.java

/**
 * Tests the given {@code real} classifier against the given oracle using the given
 * {@link Parser} to provide the {@code real} labeled testing data.
 *
 * This method uses root-mean-square error as the evaluation criteria.
 *
 * @param tester An object of this class
 * @param classifier The classifier to be tested.
 * @param oracle The classifier to test against.
 * @param parser The parser supplying the labeled example objects.
 * @param output Whether or not to produce output on {@code stdout}.
 * @param outputGranularity The number of examples processed in between time stamp messages.
 *///  ww  w.  j a v  a  2  s .com
public static void testReal(TestReal tester, Classifier classifier, Classifier oracle, Parser parser,
        boolean output, int outputGranularity) {

    int processed = 1;
    long totalTime = 0;
    Runtime runtime = null;

    if (output && outputGranularity > 0) {
        runtime = Runtime.getRuntime();
        System.out.println("0 examples tested at " + new Date());
        System.out.println("Total memory before first example: " + runtime.totalMemory());

        Object example = parser.next();
        if (example == null)
            return;

        totalTime -= System.currentTimeMillis();
        double prediction = classifier.realValue(example);
        totalTime += System.currentTimeMillis();
        System.out.println("First example processed in " + (totalTime / 1000.0) + " seconds.");
        System.out.println("Total memory after first example: " + runtime.totalMemory());

        double gold = oracle.realValue(example);
        tester.reportPrediction(prediction, gold);

        for (example = parser.next(); example != null; example = parser.next(), ++processed) {
            if (processed % outputGranularity == 0) {
                System.out.println(processed + " examples tested at " + new Date());
            }

            totalTime -= System.currentTimeMillis();
            prediction = classifier.realValue(example);
            totalTime += System.currentTimeMillis();

            gold = oracle.realValue(example);

            tester.reportPrediction(prediction, gold);
        }

        System.out.println(processed + " examples tested at " + new Date() + "\n");
    } else {
        if (output) {
            runtime = Runtime.getRuntime();
            System.out.println("Total memory before first example: " + runtime.totalMemory());
        }

        Object example = parser.next();
        if (example == null)
            return;

        totalTime -= System.currentTimeMillis();
        double prediction = classifier.realValue(example);
        totalTime += System.currentTimeMillis();

        if (output) {
            System.out.println("First example processed in " + (totalTime / 1000.0) + " seconds.");
            System.out.println("Total memory after first example: " + runtime.totalMemory());
        }

        double gold = oracle.realValue(example);

        tester.reportPrediction(prediction, gold);

        for (example = parser.next(); example != null; example = parser.next(), ++processed) {
            totalTime -= System.currentTimeMillis();
            prediction = classifier.realValue(example);
            totalTime += System.currentTimeMillis();

            gold = oracle.realValue(example);

            tester.reportPrediction(prediction, gold);
        }
    }

    if (output) {
        System.out.println("Average evaluation time: " + (totalTime / (1000.0 * processed)) + " seconds\n");
        tester.printPerformace(System.out, processed);
    }
}

From source file:gov.nih.nci.caarray.plugins.illumina.GenotypingProcessedMatrixHandler.java

static long tick(long lastTick, int line, Object proc) {
    final long now = System.currentTimeMillis();
    if (lastTick + ONE_MINUTE <= now) {
        final Runtime r = Runtime.getRuntime();
        LOG.info("...still processing around line " + line + " with " + proc + " free="
                + (r.freeMemory() / 1048576) + "/" + (r.totalMemory() / 1048576) + "MB");
        return now;
    }//from ww w. jav a2 s.  c om
    return lastTick;
}

From source file:org.apache.solr.common.util.TestJavaBinCodec.java

static void printMem(String head) {
    System.out.println("*************" + head + "***********");
    int mb = 1024 * 1024;
    //Getting the runtime reference from system
    Runtime runtime = Runtime.getRuntime();
    //Print used memory
    System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

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

}

From source file:org.thoughtcrime.securesms.logsubmit.SubmitLogFragment.java

public static String getMemoryUsage(Context context) {
    Runtime info = Runtime.getRuntime();
    info.totalMemory();
    return String.format(Locale.ENGLISH, "%dM (%.2f%% free, %dM max)", asMegs(info.totalMemory()),
            (float) info.freeMemory() / info.totalMemory() * 100f, asMegs(info.maxMemory()));
}

From source file:com.baasbox.metrics.BaasBoxMetric.java

private static void setGauges() {
    //memory gauges
    registry.register(name(GAUGE_MEMORY_MAX_ALLOCABLE), new CachedGauge<Long>(10, TimeUnit.MINUTES) {
        @Override//from  w w w.j a va2s . c  om
        public Long loadValue() {
            Runtime rt = Runtime.getRuntime();
            long maxMemory = rt.maxMemory();
            return maxMemory;
        }
    });

    registry.register(name(GAUGE_MEMORY_CURRENT_ALLOCATE), new Gauge<Long>() {
        @Override
        public Long getValue() {
            Runtime rt = Runtime.getRuntime();
            long totalMemory = rt.totalMemory();
            return totalMemory;
        }
    });

    registry.register(name(GAUGE_MEMORY_USED), new Gauge<Long>() {
        @Override
        public Long getValue() {
            Runtime rt = Runtime.getRuntime();
            long freeMemory = rt.freeMemory();
            long totalMemory = rt.totalMemory();
            return totalMemory - freeMemory;
        }
    });
    registry.register(name(GAUGE_FILESYSTEM_DATAFILE_SPACE_LEFT),
            new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public Long loadValue() {
                    return new File(BBConfiguration.getDBDir()).getFreeSpace();
                }
            });

    registry.register(name(GAUGE_FILESYSTEM_BACKUPDIR_SPACE_LEFT),
            new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public Long loadValue() {
                    return new File(BBConfiguration.getDBBackupDir()).getFreeSpace();
                }
            });

    registry.register(name(GAUGE_DB_DATA_SIZE), new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
        @Override
        public Long loadValue() {
            boolean opened = false;
            try {
                if (DbHelper.getConnection() == null || DbHelper.getConnection().isClosed()) {
                    DbHelper.open(BBConfiguration.getAPPCODE(), BBConfiguration.getBaasBoxAdminUsername(),
                            BBConfiguration.getBaasBoxAdminUsername());
                    opened = true;
                }
                return DbHelper.getConnection().getSize();
            } catch (InvalidAppCodeException e) {
                throw new RuntimeException(e);
            } finally {
                if (opened)
                    DbHelper.close(DbHelper.getConnection());
            }
        }
    });

    registry.register(name(GAUGE_DB_DATA_DIRECTORY_SIZE),
            new CachedGauge<Long>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public Long loadValue() {
                    return FileUtils.sizeOfDirectory(new File(BBConfiguration.getDBDir()));
                }
            });
    registry.register(name(GAUGE_DB_MAX_SIZE_THRESHOLD),
            new CachedGauge<BigInteger>(CACHE_TIMEOUT, TimeUnit.MINUTES) {
                @Override
                public BigInteger loadValue() {
                    return BBConfiguration.getDBSizeThreshold();
                }
            });

}

From source file:org.apache.accumulo.server.gc.SimpleGarbageCollector.java

static public boolean almostOutOfMemory() {
    Runtime runtime = Runtime.getRuntime();
    return runtime.totalMemory() - runtime.freeMemory() > CANDIDATE_MEMORY_PERCENTAGE * runtime.maxMemory();
}