List of usage examples for java.lang Runtime totalMemory
public native long totalMemory();
From source file:org.mrgeo.resources.wms.WmsGenerator.java
private Response handleRequest(@Context UriInfo uriInfo) { long start = System.currentTimeMillis(); try {//from w w w.j a v a 2 s. com MultivaluedMap<String, String> allParams = uriInfo.getQueryParameters(); String request = getQueryParam(allParams, "request", "GetCapabilities"); ProviderProperties providerProperties = SecurityUtils.getProviderProperties(); String serviceName = getQueryParam(allParams, "service"); if (serviceName == null) { return writeError(Response.Status.BAD_REQUEST, "Missing required SERVICE parameter. Should be set to \"WMS\""); } if (!serviceName.equalsIgnoreCase("wms")) { return writeError(Response.Status.BAD_REQUEST, "Invalid SERVICE parameter. Should be set to \"WMS\""); } if (request.equalsIgnoreCase("getmap")) { return getMap(allParams, providerProperties); } else if (request.equalsIgnoreCase("getmosaic")) { return getMosaic(allParams, providerProperties); } else if (request.equalsIgnoreCase("gettile")) { return getTile(allParams, providerProperties); } else if (request.equalsIgnoreCase("getcapabilities")) { return getCapabilities(uriInfo, allParams, providerProperties); } else if (request.equalsIgnoreCase("describetiles")) { return describeTiles(uriInfo, allParams, providerProperties); } return writeError(Response.Status.BAD_REQUEST, "Invalid request"); } finally { if (log.isDebugEnabled()) { log.debug("WMS request time: {}ms", (System.currentTimeMillis() - start)); // this can be resource intensive. System.gc(); final Runtime rt = Runtime.getRuntime(); log.debug(String.format("WMS request memory: %.1fMB / %.1fMB\n", (rt.totalMemory() - rt.freeMemory()) / 1e6, rt.maxMemory() / 1e6)); } } }
From source file:spade.reporter.CDM.java
private void printStats() { Runtime runtime = Runtime.getRuntime(); long usedMemoryMB = (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024); long internalBufferSize = getBuffer().size(); logger.log(Level.INFO, "Lines read: {0}, Internal buffer size: {1}, JVM memory in use: {2}MB", new Object[] { linesRead, internalBufferSize, usedMemoryMB }); }
From source file:org.jkiss.dbeaver.core.application.DBeaverApplication.java
@Override public Object start(IApplicationContext context) { instance = this; Display display = null;//from w w w .java 2 s.com 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: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();// w ww . j a va 2 s.co m 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:im.neon.activity.CommonActivityUtils.java
/** * Log the memory statuses./*from ww w . j a va 2 s .c o m*/ * * @param activity the calling activity * @return if the device is running on low memory. */ public static boolean displayMemoryInformation(Activity activity, String title) { long freeSize = 0L; long totalSize = 0L; long usedSize = -1L; try { Runtime info = Runtime.getRuntime(); freeSize = info.freeMemory(); totalSize = info.totalMemory(); usedSize = totalSize - freeSize; } catch (Exception e) { e.printStackTrace(); } Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------"); Log.e(LOW_MEMORY_LOG_TAG, "----------- " + title + " -----------------"); Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------"); Log.e(LOW_MEMORY_LOG_TAG, "usedSize " + (usedSize / 1048576L) + " MB"); Log.e(LOW_MEMORY_LOG_TAG, "freeSize " + (freeSize / 1048576L) + " MB"); Log.e(LOW_MEMORY_LOG_TAG, "totalSize " + (totalSize / 1048576L) + " MB"); Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------"); if (null != activity) { ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE); activityManager.getMemoryInfo(mi); Log.e(LOW_MEMORY_LOG_TAG, "availMem " + (mi.availMem / 1048576L) + " MB"); Log.e(LOW_MEMORY_LOG_TAG, "totalMem " + (mi.totalMem / 1048576L) + " MB"); Log.e(LOW_MEMORY_LOG_TAG, "threshold " + (mi.threshold / 1048576L) + " MB"); Log.e(LOW_MEMORY_LOG_TAG, "lowMemory " + (mi.lowMemory)); Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------"); return mi.lowMemory; } else { return false; } }
From source file:com.streamsets.datacollector.event.handler.remote.RemoteEventHandlerTask.java
private ClientEvent getStartupReportEvent() { List<StageInfo> stageInfoList = new ArrayList<StageInfo>(); for (StageDefinition stageDef : stageLibrary.getStages()) { stageInfoList.add(new StageInfo(stageDef.getName(), stageDef.getVersion(), stageDef.getLibrary())); }//w w w. j a v a2 s . c om BuildInfo buildInfo = new DataCollectorBuildInfo(); Runtime runtime = Runtime.getRuntime(); SDCInfoEvent sdcInfoEvent = new SDCInfoEvent(runtimeInfo.getId(), runtimeInfo.getBaseHttpUrl(), System.getProperty("java.runtime.version"), stageInfoList, new SDCBuildInfo(buildInfo.getVersion(), buildInfo.getBuiltBy(), buildInfo.getBuiltDate(), buildInfo.getBuiltRepoSha(), buildInfo.getSourceMd5Checksum()), labelList, OFFSET_PROTOCOL_VERSION, Strings.emptyToNull(runtimeInfo.getDeploymentId()), runtime.totalMemory()); return new ClientEvent(UUID.randomUUID().toString(), appDestinationList, false, false, EventType.SDC_INFO_EVENT, sdcInfoEvent, null); }
From source file:pl.edu.icm.visnow.system.main.VisNow.java
public long getMemoryAvailable() { Runtime r = Runtime.getRuntime(); r.gc();/* ww w .j a va 2 s . c om*/ long total = r.totalMemory(); long free = r.freeMemory(); long used = total - free; return (memoryMax - used); }
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:elaborate.editor.model.orm.service.ProjectService.java
void logMemory() { int mb = 1024 * 1024; System.gc();//from w w w . j a v a 2 s.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.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 ww.j a v a2s. c o m*/ 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()))); } }