List of usage examples for java.lang Runtime maxMemory
public native long maxMemory();
From source file:tectonicus.world.World.java
public void dumpMemStats() { System.out.println("---------------"); System.out.println("World Mem Stats"); System.out.println("---------------"); // System.out.println("Total chunks: "+chunks.size()); System.out.println("Loaded raw chunks: " + rawLoadedChunks.size()); System.out.println("Loaded geometry chunks: " + geometryLoadedChunks.size()); long rawMemTotal = rawLoadedChunks.getRawMemorySize(); rawMemTotal = rawMemTotal / 1024 / 1024; // bytes to megabytes System.out.println("Estimated raw memory: " + rawMemTotal + " Mb"); long geometryMemTotal = geometryLoadedChunks.getGeometryMemorySize(); geometryMemTotal = geometryMemTotal / 1024 / 1024; // bytes to megabytes System.out.println("Estimated geometry memory: " + geometryMemTotal + " Mb"); System.out.println();/*from ww w . j a v a 2s . c om*/ Runtime runtime = Runtime.getRuntime(); final long maxMemory = runtime.maxMemory(); final long allocatedMemory = runtime.totalMemory(); final long freeMemory = runtime.freeMemory(); NumberFormat format = NumberFormat.getInstance(); System.out.println("Max memory: " + format.format(maxMemory / 1024.0f) + "Mb"); System.out.println("Allocated memory: " + format.format(allocatedMemory / 1024.0f) + "Mb"); System.out.println("Free memory: " + format.format(freeMemory / 1024.0f) + "Mb"); /* System.out.println("Geometry stats:"); for (Chunk c : geometryLoadedChunks.values()) { c.printGeometryStats(); } */ }
From source file:org.apache.ignite.testframework.junits.IgniteConfigVariationsAbstractTest.java
/** * Prints memory usage./* www .ja v a2 s . c om*/ */ private void memoryUsage() { int mb = 1024 * 1024; Runtime runtime = Runtime.getRuntime(); info("##### Heap utilization statistics [MB] #####"); info("Used Memory (mb): " + (runtime.totalMemory() - runtime.freeMemory()) / mb); info("Free Memory (mb): " + runtime.freeMemory() / mb); info("Total Memory (mb): " + runtime.totalMemory() / mb); info("Max Memory (mb): " + runtime.maxMemory() / mb); }
From source file:org.jkiss.dbeaver.core.application.DBeaverApplication.java
@Override public Object start(IApplicationContext context) { instance = this; Display display = null;//from w ww . j a v a 2 s. c o m Location instanceLoc = Platform.getInstanceLocation(); //log.debug("Default instance location: " + instanceLoc.getDefault()); String defaultHomePath = getDefaultWorkspaceLocation().getAbsolutePath(); try { URL defaultHomeURL = new URL("file", //$NON-NLS-1$ null, defaultHomePath); boolean keepTrying = true; while (keepTrying) { if (!instanceLoc.set(defaultHomeURL, true)) { if (handleCommandLine(defaultHomePath)) { return IApplication.EXIT_OK; } // Can't lock specified path if (display == null) { display = PlatformUI.createDisplay(); } Shell shell = new Shell(display, SWT.ON_TOP); MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.IGNORE | SWT.RETRY | SWT.ABORT); messageBox.setText("DBeaver - Can't lock workspace"); messageBox.setMessage("Can't lock workspace at " + defaultHomePath + ".\n" + "It seems that you have another DBeaver instance running.\n" + "You may ignore it and work without lock but it is recommended to shutdown previous instance otherwise you may corrupt workspace data."); int msgResult = messageBox.open(); shell.dispose(); switch (msgResult) { case SWT.ABORT: return IApplication.EXIT_OK; case SWT.IGNORE: instanceLoc.set(defaultHomeURL, false); keepTrying = false; break; case SWT.RETRY: break; } } else { break; } } } catch (Throwable e) { // Just skip it // Error may occur if -data parameter was specified at startup System.err.println("Can't switch workspace to '" + defaultHomePath + "' - " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } Bundle brandingBundle = context.getBrandingBundle(); if (brandingBundle != null) { BundleContext bundleContext = brandingBundle.getBundleContext(); if (bundleContext != null) { bundleContext.addBundleListener(new BundleListener() { @Override public void bundleChanged(BundleEvent event) { String message = null; if (event.getType() == BundleEvent.STARTED) { message = "> Start " + event.getBundle().getSymbolicName() + " [" + event.getBundle().getVersion() + "]"; } else if (event.getType() == BundleEvent.STOPPED) { message = "< Stop " + event.getBundle().getSymbolicName() + " [" + event.getBundle().getVersion() + "]"; } if (message != null) { log.debug(message); } } }); } } Log.addListener(new Log.Listener() { @Override public void loggedMessage(Object message, Throwable t) { DBeaverSplashHandler.showMessage(CommonUtils.toString(message)); } }); final Runtime runtime = Runtime.getRuntime(); // Init Core plugin and mark it as standalone version DBeaverCore.setApplication(this); initDebugWriter(); log.debug(DBeaverCore.getProductTitle() + " is starting"); //$NON-NLS-1$ log.debug("Install path: '" + SystemVariablesResolver.getInstallPath() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("Instance path: '" + instanceLoc.getURL() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ log.debug("Memory available " + (runtime.totalMemory() / (1024 * 1024)) + "Mb/" + (runtime.maxMemory() / (1024 * 1024)) + "Mb"); // Run instance server instanceServer = DBeaverInstanceServer.startInstanceServer(); // Set default resource encoding to UTF-8 String defEncoding = DBeaverCore.getGlobalPreferenceStore() .getString(DBeaverPreferences.DEFAULT_RESOURCE_ENCODING); if (CommonUtils.isEmpty(defEncoding)) { defEncoding = GeneralUtils.UTF8_ENCODING; } ResourcesPlugin.getPlugin().getPluginPreferences().setValue(ResourcesPlugin.PREF_ENCODING, defEncoding); // Create display if (display == null) { log.debug("Initialize display"); display = PlatformUI.createDisplay(); } // Prefs default PlatformUI.getPreferenceStore().setDefault(IWorkbenchPreferenceConstants.KEY_CONFIGURATION_ID, ApplicationWorkbenchAdvisor.DBEAVER_SCHEME_NAME); try { int returnCode = PlatformUI.createAndRunWorkbench(display, createWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) { return IApplication.EXIT_RESTART; } return IApplication.EXIT_OK; } finally { /* try { Job.getJobManager().join(null, new NullProgressMonitor()); } catch (InterruptedException e) { e.printStackTrace(); } */ display.dispose(); } }
From source file:net.sf.nmedit.nomad.core.Nomad.java
public void debug_gc() { SwingUtilities.invokeLater(new Runnable() { public void run() { Runtime rt = Runtime.getRuntime(); System.out.println("garbage collect"); System.gc();/*from w w w.j a va 2s. c o m*/ System.out.println("gc: free:" + rt.freeMemory() + " byte, max:" + rt.maxMemory()); } }); }
From source file:uk.ac.ebi.phenotype.solr.indexer.IndexerManager.java
/** * Print the jvm memory configuration./* ww w . ja va 2 s . c o m*/ */ private void printJvmMemoryConfiguration() { final int mb = 1024 * 1024; Runtime runtime = Runtime.getRuntime(); DecimalFormat formatter = new DecimalFormat("#,###"); logger.info("Used memory : " + (formatter.format(runtime.totalMemory() - runtime.freeMemory() / mb))); logger.info("Free memory : " + formatter.format(runtime.freeMemory())); logger.info("Total memory: " + formatter.format(runtime.totalMemory())); logger.info("Max memory : " + formatter.format(runtime.maxMemory())); }
From source file:de.evaluationtool.gui.EvaluationFrame.java
public void updateTitle() { int mb = 1024 * 1024; Runtime runtime = Runtime.getRuntime(); int used = (int) ((runtime.totalMemory() - runtime.freeMemory()) / mb); int max = (int) ((runtime.maxMemory() - runtime.freeMemory()) / mb); this.setTitle(DEFAULT_TITLE + " (" + sampleSize + '/' + cellPanels.size() + ") " + dataSourceName1 + '-' + dataSourceName2 + " RAM usage (" + used + "/" + max + ") MB"); }
From source file:org.schedulesdirect.grabber.Grabber.java
private void updateZip(NetworkEpgClient clnt) throws IOException, JSONException, JsonParseException { Set<String> completedListings = new HashSet<String>(); LOG.debug(String.format("Using %d worker threads", globalOpts.getMaxThreads())); pool = createThreadPoolExecutor();//from w w w. j a v a2 s . c om start = System.currentTimeMillis(); File dest = grabOpts.getTarget(); cachedSeriesIds = new HashSet<String>(); boolean rmDest = false; if (dest.exists()) { ZipEpgClient zipClnt = null; try { zipClnt = new ZipEpgClient(dest); if (!zipClnt.getUserStatus().getLastServerRefresh() .before(clnt.getUserStatus().getLastServerRefresh())) { LOG.info( "Current cache file contains latest data from Schedules Direct server; use --force-download to force a new download from server."); boolean force = grabOpts.isForce(); if (!force) return; else LOG.warn("Forcing an update of data with the server due to user request!"); } } catch (Exception e) { if (grabOpts.isKeep()) { LOG.error("Existing cache is invalid, keeping by user request!", e); return; } else { LOG.warn("Existing cache is invalid, deleting it; use --keep-bad-cache to keep existing cache!", e); rmDest = true; } } finally { if (zipClnt != null) try { zipClnt.close(); } catch (IOException e) { } if (rmDest && !dest.delete()) throw new IOException("Unable to delete " + dest); } } freshZip = !dest.exists(); try (FileSystem vfs = FileSystems.newFileSystem(new URI(String.format("jar:%s", dest.toURI())), Collections.singletonMap("create", "true"))) { if (freshZip) { Path target = vfs.getPath(ZipEpgClient.ZIP_VER_FILE); Files.write(target, Integer.toString(ZipEpgClient.ZIP_VER).getBytes(ZipEpgClient.ZIP_CHARSET)); } ProgramCache progCache = ProgramCache.get(vfs); Path lineups = vfs.getPath("lineups.txt"); Files.deleteIfExists(lineups); Path scheds = vfs.getPath("/schedules/"); if (!Files.isDirectory(scheds)) Files.createDirectory(scheds); Path maps = vfs.getPath("/maps/"); PathUtils.removeDirectory(maps); Files.createDirectory(maps); Path progs = vfs.getPath("/programs/"); if (!Files.isDirectory(progs)) Files.createDirectory(progs); Path logos = vfs.getPath("/logos/"); if (!Files.isDirectory(logos)) Files.createDirectory(logos); Path md5s = vfs.getPath("/md5s/"); if (!Files.isDirectory(md5s)) Files.createDirectory(md5s); Path cache = vfs.getPath(LOGO_CACHE); if (Files.exists(cache)) { String cacheData = new String(Files.readAllBytes(cache), ZipEpgClient.ZIP_CHARSET); logoCache = Config.get().getObjectMapper().readValue(cacheData, JSONObject.class); } else logoCache = new JSONObject(); Path seriesInfo = vfs.getPath("/seriesInfo/"); if (!Files.isDirectory(seriesInfo)) Files.createDirectories(seriesInfo); loadSeriesInfoIds(seriesInfo); missingSeriesIds = Collections.synchronizedSet(new HashSet<String>()); loadRetryIds(vfs.getPath(SERIES_INFO_DATA)); JSONObject resp = Config.get().getObjectMapper().readValue( factory.get(DefaultJsonRequest.Action.GET, RestNouns.LINEUPS, clnt.getHash(), clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null), JSONObject.class); if (!JsonResponseUtils.isErrorResponse(resp)) Files.write(lineups, resp.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); else LOG.error("Received error response when requesting lineup data!"); for (Lineup l : clnt.getLineups()) { buildStationList(); JSONObject o = Config.get().getObjectMapper() .readValue( factory.get(DefaultJsonRequest.Action.GET, l.getUri(), clnt.getHash(), clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null), JSONObject.class); Files.write(vfs.getPath("/maps", ZipEpgClient.scrubFileName(String.format("%s.txt", l.getId()))), o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); JSONArray stations = o.getJSONArray("stations"); JSONArray ids = new JSONArray(); for (int i = 0; i < stations.length(); ++i) { JSONObject obj = stations.getJSONObject(i); String sid = obj.getString("stationID"); if (stationList != null && !stationList.contains(sid)) LOG.debug(String.format("Skipped %s; not listed in station file", sid)); else if (completedListings.add(sid)) { ids.put(sid); if (!grabOpts.isNoLogos()) { if (logoCacheInvalid(obj)) pool.execute(new LogoTask(obj, vfs, logoCache)); else if (LOG.isDebugEnabled()) LOG.debug(String.format("Skipped logo for %s; already cached!", obj.optString("callsign", null))); } else if (!logosWarned) { logosWarned = true; LOG.warn("Logo downloads disabled by user request!"); } } else LOG.debug(String.format("Skipped %s; already downloaded.", sid)); //pool.setMaximumPoolSize(5); // Processing these new schedules takes all kinds of memory! if (ids.length() == grabOpts.getMaxSchedChunk()) { pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory)); ids = new JSONArray(); } } if (ids.length() > 0) pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory)); } pool.shutdown(); try { LOG.debug("Waiting for SchedLogoExecutor to terminate..."); if (pool.awaitTermination(15, TimeUnit.MINUTES)) LOG.debug("SchedLogoExecutor: Terminated successfully."); else { failedTask = true; LOG.warn( "SchedLogoExecutor: Termination timed out; some tasks probably didn't finish properly!"); } } catch (InterruptedException e) { failedTask = true; LOG.warn( "SchedLogoExecutor: Termination interrupted); some tasks probably didn't finish properly!"); } Files.write(cache, logoCache.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.CREATE); ScheduleTask.commit(vfs); pool = createThreadPoolExecutor(); //pool.setMaximumPoolSize(5); // Again, we've got memory problems String[] dirtyPrograms = progCache.getDirtyIds(); progCache.markAllClean(); progCache = null; LOG.info(String.format("Identified %d program ids requiring an update!", dirtyPrograms.length)); Collection<String> progIds = new ArrayList<String>(); for (String progId : dirtyPrograms) { progIds.add(progId); if (progIds.size() == grabOpts.getMaxProgChunk()) { pool.execute(new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false)); progIds.clear(); } } if (progIds.size() > 0) pool.execute( new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false)); pool.shutdown(); try { LOG.debug("Waiting for ProgramExecutor to terminate..."); if (pool.awaitTermination(15, TimeUnit.MINUTES)) { LOG.debug("ProgramExecutor: Terminated successfully."); Iterator<String> itr = missingSeriesIds.iterator(); while (itr.hasNext()) { String id = itr.next(); if (cachedSeriesIds.contains(id)) itr.remove(); } if (missingSeriesIds.size() > 0) { LOG.info(String.format("Grabbing %d series info programs!", missingSeriesIds.size())); Set<String> retrySet = new HashSet<>(); try { new ProgramTask(missingSeriesIds, vfs, clnt, factory, missingSeriesIds, "seriesInfo", retrySet, true).run(); } catch (RuntimeException e) { LOG.error("SeriesInfo task failed!", e); Grabber.failedTask = true; } Path seriesInfoData = vfs.getPath(SERIES_INFO_DATA); if (retrySet.size() > 0) { StringBuilder sb = new StringBuilder(); for (String id : retrySet) sb.append(id + "\n"); Files.write(seriesInfoData, sb.toString().getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } else if (Files.exists(seriesInfoData)) Files.delete(seriesInfoData); } } else { failedTask = true; LOG.warn("ProgramExecutor: Termination timed out; some tasks probably didn't finish properly!"); } } catch (InterruptedException e) { failedTask = true; LOG.warn("ProgramExecutor: Termination interrupted); some tasks probably didn't finish properly!"); } String userData = clnt.getUserStatus().toJson(); if (failedTask) { LOG.error("One or more tasks failed! Resetting last data refresh timestamp to zero."); SimpleDateFormat fmt = Config.get().getDateTimeFormat(); String exp = fmt.format(new Date(0L)); JSONObject o = Config.get().getObjectMapper().readValue(userData, JSONObject.class); o.put("lastDataUpdate", exp); userData = o.toString(2); } Path p = vfs.getPath(USER_DATA); Files.write(p, userData.getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); removeIgnoredStations(vfs); } catch (URISyntaxException e1) { throw new RuntimeException(e1); } finally { Runtime rt = Runtime.getRuntime(); LOG.info(String.format("MemStats:%n\tFREE: %s%n\tUSED: %s%n\t MAX: %s", FileUtils.byteCountToDisplaySize(rt.freeMemory()), FileUtils.byteCountToDisplaySize(rt.totalMemory()), FileUtils.byteCountToDisplaySize(rt.maxMemory()))); } }
From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java
private void returnHealth(HttpServletResponse response) throws Exception { StringBuffer healthInfo = new StringBuffer(); healthInfo.append("AjaxToaster version " + getVersion() + "<br>"); healthInfo.append("Using XMLToaster version " + com.inverse2.xmltoaster.Version.getVersion() + "<br>"); healthInfo.append("Properties file name [" + propertiesPath + "]<br>"); healthInfo.append("Script directory [" + scriptPath + "]<br>"); healthInfo.append("Logging method [" + loggingType + "]<br>"); healthInfo.append("Sleep interval [" + sleepInterval + "]<br>"); healthInfo.append("<br>"); healthInfo.append(serviceMapper.getURIMappings().replaceAll("\\n", "<br>")); healthInfo.append("<br>"); healthInfo.append("List of operations available;<br><br>"); List<ServiceOperationInfo> serviceList = servicePool.getOperationInfo(); ServiceOperationInfo operation;/*from w ww . j a va2 s . c om*/ for (Iterator<ServiceOperationInfo> it = serviceList.iterator(); it.hasNext();) { operation = it.next(); healthInfo.append("-- " + operation.getServiceName() + "/" + operation.getOperationName() + "<br>"); } Runtime rt = Runtime.getRuntime(); healthInfo.append("<br>JVM: Total Mem [" + rt.totalMemory() + "], Free Mem [" + rt.freeMemory() + "], Max Mem [" + rt.maxMemory() + "]<br>"); writeResponse(healthInfo.toString(), "HTML", null, response); }
From source file:elaborate.editor.model.orm.service.ProjectService.java
void logMemory() { int mb = 1024 * 1024; System.gc();//from w w w . ja v a2s. c o m // 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.tez.dag.app.TestMockDAGAppMaster.java
private void checkMemory(String name, MockDAGAppMaster mockApp) { long mb = 1024 * 1024; //Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); System.out.println("##### Heap utilization statistics [MB] for " + name); runtime.gc();/*from w ww .jav a2 s .c om*/ //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); }