List of usage examples for java.lang Runtime maxMemory
public native long maxMemory();
From source file:edu.stanford.muse.util.Util.java
public static String getMemoryStats() { Runtime r = Runtime.getRuntime(); System.gc();//from ww w. j a va 2s . c o m int MB = 1024 * 1024; return r.freeMemory() / MB + " MB free, " + (r.totalMemory() / MB - r.freeMemory() / MB) + " MB used, " + r.maxMemory() / MB + " MB max, " + r.totalMemory() / MB + " MB total"; }
From source file:de.hpi.fgis.hdrs.node.Node.java
@Override public NodeStatus getNodeStatus() { Runtime rt = Runtime.getRuntime(); return new NodeStatus(rt.freeMemory() + (rt.maxMemory() - rt.totalMemory()), bufferSize.get(), conf.getInt(Configuration.KEY_NODE_TRANSACTION_BUFFER, Configuration.DEFAULT_NODE_TRANSACTION_BUFFER) - transactionMemPool.availablePermits(), segments.size(), transactions.size(), scanners.size()); }
From source file:org.pentaho.di.core.Const.java
/** * Return the percentage of free memory for this JVM. * * @return Percentage of free memory.// w ww. ja 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.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());/* ww w . ja v a 2 s. c o 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: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: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;// www .j a v a 2 s.c om //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:cn.nukkit.Server.java
public void titleTick() { if (true || !Nukkit.ANSI) { return;/* w w w . ja v a2 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:de.dal33t.powerfolder.Controller.java
/** * Starts controller with a special config file, and creates and starts all * components of PowerFolder.//from ww w . j av a2 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.apache.accumulo.server.tabletserver.ScanRunState.java
private synchronized static void logGCInfo(AccumuloConfiguration conf) { List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans(); Runtime rt = Runtime.getRuntime(); StringBuilder sb = new StringBuilder("gc"); boolean sawChange = false; long maxIncreaseInCollectionTime = 0; for (GarbageCollectorMXBean gcBean : gcmBeans) { Long prevTime = prevGcTime.get(gcBean.getName()); long pt = 0; if (prevTime != null) { pt = prevTime;/*from w w w . jav a 2 s . c om*/ } long time = gcBean.getCollectionTime(); if (time - pt != 0) { sawChange = true; } long increaseInCollectionTime = time - pt; sb.append(String.format(" %s=%,.2f(+%,.2f) secs", gcBean.getName(), time / 1000.0, increaseInCollectionTime / 1000.0)); maxIncreaseInCollectionTime = Math.max(increaseInCollectionTime, maxIncreaseInCollectionTime); prevGcTime.put(gcBean.getName(), time); } long mem = rt.freeMemory(); if (maxIncreaseInCollectionTime == 0) { gcTimeIncreasedCount = 0; } else { gcTimeIncreasedCount++; if (gcTimeIncreasedCount > 3 && mem < rt.maxMemory() * 0.05) { log.warn("Running low on memory"); gcTimeIncreasedCount = 0; } } if (mem > lastMemorySize) { sawChange = true; } String sign = "+"; if (mem - lastMemorySize <= 0) { sign = ""; } sb.append(String.format(" freemem=%,d(%s%,d) totalmem=%,d", mem, sign, (mem - lastMemorySize), rt.totalMemory())); if (sawChange) { log.debug(sb.toString()); } final long keepAliveTimeout = conf.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT); if (maxIncreaseInCollectionTime > keepAliveTimeout) { Halt.halt("Garbage collection may be interfering with lock keep-alive. Halting.", -1); } lastMemorySize = mem; }
From source file:com.skytree.epubtest.BookViewActivity.java
public void reportMemory() { Runtime rt = Runtime.getRuntime(); long maxMemory = rt.maxMemory(); // Log.v("EPub", "maxMemory:" + Long.toString(maxMemory)); ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); int memoryClass = am.getMemoryClass(); // Log.v("EPub", "memoryClass:" + Integer.toString(memoryClass)); ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); MemoryInfo memoryInfo = new MemoryInfo(); activityManager.getMemoryInfo(memoryInfo); // Log.i("EPub", "AvailMem" + memoryInfo.availMem); long memoryAvail = memoryInfo.availMem; long memoryAlloc = maxMemory - memoryAvail; String message = String.format("Max :%d Avail:%d", maxMemory, memoryAvail); showToast(message);// w w w . j av a2s . c o m }