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:org.pentaho.di.core.Const.java

/**
 * Return the percentage of free memory for this JVM.
 *
 * @return Percentage of free memory./*from w  w  w  .j  a  v a 2  s  .  co  m*/
 */
public static final int getPercentageFreeMemory() {
    Runtime runtime = Runtime.getRuntime();
    long maxMemory = runtime.maxMemory();
    long allocatedMemory = runtime.totalMemory();
    long freeMemory = runtime.freeMemory();
    long totalFreeMemory = (freeMemory + (maxMemory - allocatedMemory));

    int percentage = (int) Math.round(100 * (double) totalFreeMemory / maxMemory);

    return percentage;
}

From source file:com.lifehackinnovations.siteaudit.FloorPlanActivity.java

public Bitmap resizedbitmaponmemorycheck() {
    int width = (int) view.bitwidth[view.fp];
    int height = (int) view.bitheight[view.fp];

    final Runtime rt = Runtime.getRuntime();
    Log.d("free memory, maxmemory, total memory",
            rt.freeMemory() + " " + rt.maxMemory() + " " + rt.totalMemory());
    final long freeMem = rt.freeMemory() + (rt.maxMemory() - rt.totalMemory());
    File file1 = new File(Tabs1.floorplanstrings.get(view.fp));
    double ratio = 0.50;

    long myResourceSize = file1.length();

    Bitmap canvasbitmap;/*from w  w w .  j ava 2 s . co  m*/
    //canvasbitmap = Bitmap.createBitmap(width, height,
    //      Bitmap.Config.ARGB_8888);
    Log.d("width and height", u.s(width) + " " + u.s(height));
    Log.d("myResourceSize, freeMem, ration", myResourceSize + " " + freeMem + " " + ratio);

    if (!u.isbluestacks()) {
        Log.d("not bluestacks", "true");
        ///This is where the app get out of memory error!!!

        canvasbitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    } else {

        FINALBITMAPSCALE = 4;
        Log.d("bluestacks", "true");
        canvasbitmap = Bitmap.createBitmap(width / FINALBITMAPSCALE, height / FINALBITMAPSCALE,
                Bitmap.Config.ARGB_8888);

    }

    return canvasbitmap;
}

From source file:xc.mst.repo.RepositoryDAO.java

private double getMemUsage() {
    Runtime r = Runtime.getRuntime();
    long maxMem = r.maxMemory() / 1048576;
    long totalMem = r.totalMemory() / 1048576;

    long freeBytes = r.freeMemory();
    long freeMem = freeBytes / 1048576;

    long usedMem = totalMem - freeMem;
    double percentageUsed = ((double) usedMem) / maxMem;

    LOG.debug("");
    LOG.debug("Free  memory: " + StringUtils.leftPad(freeMem + "", 7) + " MB.");
    LOG.debug("Used  memory: " + StringUtils.leftPad(usedMem + "", 7) + " MB.");
    LOG.debug("Total memory: " + StringUtils.leftPad(totalMem + "", 7) + " MB.");
    LOG.debug("Max'm memory: " + StringUtils.leftPad(maxMem + "", 7) + " MB.");
    LOG.debug("memory percentageUsed: " + StringUtils.leftPad(Double.toString(percentageUsed), 7));

    return percentageUsed;
}

From source file:org.unitime.timetable.onlinesectioning.server.AbstractServer.java

@Override
public long getMemUsage() {
    Runtime rt = Runtime.getRuntime();
    MemoryCounter mc = new MemoryCounter();
    DecimalFormat df = new DecimalFormat("#,##0.00");
    long total = 0; // mc.estimate(this);
    Map<String, String> info = new HashMap<String, String>();
    Class clazz = getClass();/*  www. j  a va2s  .  c o  m*/
    while (clazz != null) {
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (!Modifier.isStatic(fields[i].getModifiers())) {
                if (!fields[i].getType().isPrimitive()) {
                    fields[i].setAccessible(true);
                    try {
                        Object obj = fields[i].get(this);
                        if (obj != null) {
                            long est = estimate(mc, obj);
                            if (est > 1024)
                                info.put(clazz.getSimpleName() + "." + fields[i].getName(),
                                        df.format(est / 1024.0) + " kB"
                                                + (obj instanceof Map ? " (" + ((Map) obj).size() + " records)"
                                                        : obj instanceof Collection
                                                                ? "(" + ((Collection) obj).size() + " records)"
                                                                : ""));
                            total += est;
                        }
                    } catch (IllegalAccessException ex) {
                    } catch (ConcurrentModificationException ex) {
                    }
                }
            }
        }
        clazz = clazz.getSuperclass();
    }
    iLog.info("Total Allocated " + df.format(total / 1024.0) + " kB (of "
            + df.format((rt.totalMemory() - rt.freeMemory()) / 1048576.0) + " MB), details: "
            + ToolBox.dict2string(info, 2));
    return total;
}

From source file:com.fanniemae.ezpie.LogManager.java

protected void initializeLog() {
    // Read JVM runtime settings
    Runtime runtime = Runtime.getRuntime();
    // Read the debug template
    String template = (_logFormat == LogFormat.HTML) ? readTemplateFile(_templatePath + "Debug.txt") : "";
    _startTime = System.currentTimeMillis();
    // Create debug file
    try (FileOutputStream fos = new FileOutputStream(_logFilename, false)) {
        fos.write(template.getBytes());/*www .  j  ava2 s. co m*/
        // Add machine information
        fos.write(String
                .format(_basicLine, "Environment Information", "Started",
                        new SimpleDateFormat("MMMM d, yyyy HH:mm:ss").format(new Date()), elapsedTime())
                .getBytes());
        fos.write(String.format(_basicLine, groupString(""), "User account name",
                System.getProperty("user.name"), elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "Machine Name",
                InetAddress.getLocalHost().getHostName(), elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Version", System.getProperty("java.version"),
                elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Architecture",
                System.getProperty("sun.arch.data.model") + " bit", elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Home", System.getProperty("java.home"),
                elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "JAVA Vendor", System.getProperty("java.vendor"),
                elapsedTime()).getBytes());
        fos.write(String
                .format(_longTextLine, groupString(""), "JAVA Class Path",
                        System.getProperty("java.class.path").replace(";", ";" + _newLineTab), elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Maximum Memory",
                        String.format("%,d Megabytes", runtime.maxMemory() / 1048576), elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Total Allocated Memory",
                        String.format("%,d Megabytes reserved", runtime.totalMemory() / 1048576), elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Used Memory",
                        String.format("%,d Megabytes",
                                (runtime.totalMemory() - runtime.freeMemory()) / 1048576),
                        elapsedTime())
                .getBytes());
        fos.write(String
                .format(_basicLine, groupString(""), "JVM Free Memory",
                        String.format("%,d Megabytes", runtime.freeMemory() / 1048576), elapsedTime())
                .getBytes());
        fos.write(String.format(_basicLine, groupString(""), "Operating system name",
                System.getProperty("os.name"), elapsedTime()).getBytes());
        fos.write(String.format(_basicLine, groupString(""), "User working directory",
                System.getProperty("user.dir"), elapsedTime()).getBytes());
        fos.write(_footerByteArray);
        fos.close();
    } catch (IOException e) {
        throw new PieException(String.format("Error trying to create log file. %s", _logFilename), e);
    }
}

From source file:cn.nukkit.Server.java

public void titleTick() {
    if (true || !Nukkit.ANSI) {
        return;//  w w  w  . j ava2 s  . c  om
    }

    Runtime runtime = Runtime.getRuntime();
    double used = NukkitMath.round((double) (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024, 2);
    double max = NukkitMath.round(((double) runtime.maxMemory()) / 1024 / 1024, 2);
    String usage = Math.round(used / max * 100) + "%";
    String title = (char) 0x1b + "]0;" + this.getName() + " " + this.getNukkitVersion() + " | Online "
            + this.players.size() + "/" + this.getMaxPlayers() + " | Memory " + usage;
    if (!Nukkit.shortTitle) {
        title += " | U " + NukkitMath.round((this.network.getUpload() / 1024 * 1000), 2) + " D "
                + NukkitMath.round((this.network.getDownload() / 1024 * 1000), 2) + " kB/s";
    }
    title += " | TPS " + this.getTicksPerSecond() + " | Load " + this.getTickUsage() + "%" + (char) 0x07;

    System.out.print(title);

    this.network.resetStatistics();
}

From source file:axiom.framework.core.Application.java

/**
 * Periodically called to log thread stats for this application
 */// w  w w.j a va  2  s.com
public void printThreadStats() {
    logEvent("Thread Stats for " + name + ": " + threadgroup.activeCount() + " active");

    Runtime rt = Runtime.getRuntime();
    long free = rt.freeMemory();
    long total = rt.totalMemory();

    logEvent("Free memory: " + (free / 1024) + " kB");
    logEvent("Total memory: " + (total / 1024) + " kB");
}

From source file:mondrian.olap.Util.java

public static String printMemory(String msg) {
    final Runtime rt = Runtime.getRuntime();
    final long freeMemory = rt.freeMemory();
    final long totalMemory = rt.totalMemory();
    final StringBuilder buf = new StringBuilder(64);

    buf.append("FREE_MEMORY:");
    if (msg != null) {
        buf.append(msg);//from   w w w .  ja  v a 2 s .c o  m
        buf.append(':');
    }
    buf.append(' ');
    buf.append(freeMemory / 1024);
    buf.append("kb ");

    long hundredths = (freeMemory * 10000) / totalMemory;

    buf.append(hundredths / 100);
    hundredths %= 100;
    if (hundredths >= 10) {
        buf.append('.');
    } else {
        buf.append(".0");
    }
    buf.append(hundredths);
    buf.append('%');

    return buf.toString();
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Starts controller with a special config file, and creates and starts all
 * components of PowerFolder.//from   www.j a v  a 2 s  .  c  o m
 *
 * @param filename
 *            The filename to uses as config file (located in the
 *            "getConfigLocationBase()")
 */
public void startConfig(String filename) {
    if (started) {
        throw new IllegalStateException("Configuration already started, shutdown controller first");
    }

    additionalConnectionListeners = Collections.synchronizedList(new ArrayList<ConnectionListener>());
    started = false;
    shuttingDown = false;
    threadPool = new WrappedScheduledThreadPoolExecutor(Constants.CONTROLLER_THREADS_IN_THREADPOOL,
            new NamedThreadFactory("Controller-Thread-"));

    // Initialize resource bundle eager
    // check forced language file from commandline
    if (commandLine != null && commandLine.hasOption("f")) {
        String langfilename = commandLine.getOptionValue("f");
        try {
            ResourceBundle resourceBundle = new ForcedLanguageFileResourceBundle(langfilename);
            Translation.setResourceBundle(resourceBundle);
            logInfo("Loading language bundle from file " + langfilename);
        } catch (FileNotFoundException fnfe) {
            logSevere("forced language file (" + langfilename + ") not found: " + fnfe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        } catch (IOException ioe) {
            logSevere("forced language file io error: " + ioe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        }
    } else {
        Translation.resetResourceBundle();
    }
    Translation.getResourceBundle();

    // loadConfigFile
    if (!loadConfigFile(filename)) {
        return;
    }

    boolean isDefaultConfig = Constants.DEFAULT_CONFIG_FILE.startsWith(getConfigName());
    if (isDefaultConfig) {
        // To keep compatible with previous versions
        preferences = Preferences.userNodeForPackage(PowerFolder.class);
    } else {
        preferences = Preferences.userNodeForPackage(PowerFolder.class).node(getConfigName());

    }

    // initialize logger
    // Enabled verbose mode if in config.
    // This logs to file for analysis.
    verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
    initLogger();

    if (verbose) {
        ByteSerializer.BENCHMARK = true;
        scheduleAndRepeat(new Runnable() {
            @Override
            public void run() {
                ByteSerializer.printStats();
            }
        }, 600000L, 600000L);
        Profiling.setEnabled(false);
        Profiling.reset();
    }

    String arch = OSUtil.is64BitPlatform() ? "64bit" : "32bit";
    logFine("OS: " + System.getProperty("os.name") + " (" + arch + ')');
    logFine("Java: " + JavaVersion.systemVersion().toString() + " (" + System.getProperty("java.vendor") + ')');
    logFine("Current time: " + new Date());
    Runtime runtime = Runtime.getRuntime();
    long maxMemory = runtime.maxMemory();
    long totalMemory = runtime.totalMemory();
    logFine("Max Memory: " + Format.formatBytesShort(maxMemory) + ", Total Memory: "
            + Format.formatBytesShort(totalMemory));
    if (!Desktop.isDesktopSupported() && isUIEnabled()) {
        logWarning("Desktop utility not supported");
    }

    // If we have a new config. clear the preferences.
    clearPreferencesOnConfigSwitch();

    // Load and set http proxy settings
    HTTPProxySettings.loadFromConfig(this);

    // #2179: Load from server. How to handle timeouts?
    // Command line option -c http://are.de
    ConfigurationLoader.loadAndMergeCLI(this);
    // Config entry in file
    ConfigurationLoader.loadAndMergeConfigURL(this);
    // Read from installer temp file
    ConfigurationLoader.loadAndMergeFromInstaller(this);

    if (verbose != ConfigurationEntry.VERBOSE.getValueBoolean(this)) {
        verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
        initLogger();
    }

    // Init paused only if user expects pause to be permanent or
    // "while I work"
    int pauseSecs = ConfigurationEntry.PAUSE_RESUME_SECONDS.getValueInt(getController());
    paused = PreferencesEntry.PAUSED.getValueBoolean(this)
            && (pauseSecs == Integer.MAX_VALUE || pauseSecs == 0);

    // Now set it, just in case it was paused in permanent mode.
    PreferencesEntry.PAUSED.setValue(this, paused);

    // Load and set http proxy settings again.
    HTTPProxySettings.loadFromConfig(this);

    // Initialize branding/preconfiguration of the client
    initDistribution();
    logFine("Build time: " + getBuildTime());
    logInfo("Program version " + PROGRAM_VERSION);

    if (getDistribution().getBinaryName().toLowerCase().contains("powerfolder")) {
        Debug.writeSystemProperties();
    }

    if (ConfigurationEntry.KILL_RUNNING_INSTANCE.getValueBoolean(this)) {
        killRunningInstance();
    }
    FolderList.removeMemberFiles(this);

    // Initialize plugins
    setupProPlugins();
    pluginManager = new PluginManager(this);
    pluginManager.init();

    // create node manager
    nodeManager = new NodeManager(this);

    // Only one task brother left...
    taskManager = new PersistentTaskManager(this);

    // Folder repository
    folderRepository = new FolderRepository(this);
    setLoadingCompletion(0, 10);

    // Create transfer manager
    // If this is a unit test it might have been set before.
    try {
        transferManager = transferManagerFactory.call();
    } catch (Exception e) {
        logSevere("Exception", e);
    }

    reconnectManager = new ReconnectManager(this);
    // Create os client
    osClient = new ServerClient(this);

    if (isUIEnabled()) {
        uiController = new UIController(this);
        if (ConfigurationEntry.USER_INTERFACE_LOCKED.getValueBoolean(this)) {
            // Don't let the user pass this step.
            new UIUnLockDialog(this).openAndWait();
        }
    }

    setLoadingCompletion(10, 20);

    // The io provider.
    ioProvider = new IOProvider(this);
    ioProvider.start();

    // Set hostname by CLI
    if (commandLine != null && commandLine.hasOption('d')) {
        String host = commandLine.getOptionValue("d");
        if (StringUtils.isNotBlank(host)) {
            InetSocketAddress addr = Util.parseConnectionString(host);
            if (addr != null) {
                ConfigurationEntry.HOSTNAME.setValue(this, addr.getHostName());
                ConfigurationEntry.NET_BIND_PORT.setValue(this, addr.getPort());
            }
        }
    }

    // initialize dyndns manager
    dyndnsManager = new DynDnsManager(this);

    setLoadingCompletion(20, 30);

    // initialize listener on local port
    if (!initializeListenerOnLocalPort()) {
        return;
    }
    if (!isUIEnabled()) {
        // Disable paused function
        paused = false;
    }

    setLoadingCompletion(30, 35);

    // Start the nodemanager
    nodeManager.init();
    if (!ProUtil.isRunningProVersion()) {
        // Nodemanager gets later (re) started by ProLoader.
        nodeManager.start();
    }

    setLoadingCompletion(35, 60);
    securityManager = new SecurityManagerClient(this, osClient);

    // init repo (read folders)
    folderRepository.init();
    logInfo("Dataitems: " + Debug.countDataitems(Controller.this));
    // init of folders takes rather long so a big difference with
    // last number to get smooth bar... ;-)
    setLoadingCompletion(60, 65);

    // start repo maintainance Thread
    folderRepository.start();
    setLoadingCompletion(65, 70);

    // Start the transfer manager thread
    transferManager.start();
    setLoadingCompletion(70, 75);

    // Initalize rcon manager
    startRConManager();

    setLoadingCompletion(75, 80);

    // Start all configured listener if not in paused mode
    startConfiguredListener();
    setLoadingCompletion(80, 85);

    // open broadcast listener
    openBroadcastManager();
    setLoadingCompletion(85, 90);

    // Controller now started
    started = true;
    startTime = new Date();

    // Now taskmanager
    taskManager.start();

    logInfo("Controller started");

    // dyndns updater
    /*
     * boolean onStartUpdate = ConfigurationEntry.DYNDNS_AUTO_UPDATE
     * .getValueBoolean(this).booleanValue(); if (onStartUpdate) {
     * getDynDnsManager().onStartUpdate(); }
     */
    dyndnsManager.updateIfNessesary();

    setLoadingCompletion(90, 100);

    // Login to OS
    if (Feature.OS_CLIENT.isEnabled()) {
        try {
            osClient.loginWithLastKnown();
        } catch (Exception e) {
            logWarning("Unable to login with last known username. " + e);
            logFiner(e);
        }
    }

    // Start Plugins
    pluginManager.start();

    // open UI
    if (isConsoleMode()) {
        logFine("Running in console");
    } else {
        logFine("Opening UI");
        openUI();
    }

    // Load anything that was not handled last time.
    loadPersistentObjects();

    setLoadingCompletion(100, 100);
    if (!isConsoleMode()) {
        uiController.hideSplash();
    }

    if (ConfigurationEntry.AUTO_CONNECT.getValueBoolean(this)) {
        // Now start the connecting process
        reconnectManager.start();
    } else {
        logFine("Not starting reconnection process. " + "Config auto.connect set to false");
    }
    // Start connecting to OS client.
    if (Feature.OS_CLIENT.isEnabled() && ConfigurationEntry.SERVER_CONNECT.getValueBoolean(this)) {
        osClient.start();
    } else {
        logInfo("Not connecting to server (" + osClient.getServerString() + "): Disabled");
    }

    // Setup our background working tasks
    setupPeriodicalTasks();

    if (MacUtils.isSupported()) {
        if (isFirstStart()) {
            MacUtils.getInstance().setPFStartup(true, this);
        }
        MacUtils.getInstance().setAppReOpenedListener(this);
    }

    if (pauseSecs == 0) {
        // Activate adaptive logic
        setPaused(paused);
    }
}

From source file:org.wyona.yanel.servlet.YanelServlet.java

/**
 * Get currently used memory//from   w  ww  .  j  a v a2s  .  c om
 */
private long getUsedMemory(Runtime rt) {
    return (rt.totalMemory() - rt.freeMemory()) / 1024 / 1024;
}