List of usage examples for java.lang Runtime totalMemory
public native long totalMemory();
From source file:br.gov.lexml.server.LexMLOAIHandler.java
/** * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do * the actual work of the verb.//w ww .jav a 2s .c om * * @param request the servlet's request information * @param response the servlet's response information * @exception IOException an I/O error occurred */ @Override public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException { // Fora gerao do cookie de sesso // (necessrio para balanceamento de carga pelo pound do Prodasen) request.getSession(); HashMap attributes = getAttributes(request.getPathInfo()); if (!filterRequest(request, response)) { return; } log.debug("attributes = " + attributes); Properties properties = (Properties) attributes.get("OAIHandler.properties"); boolean monitor = false; if (properties.getProperty("OAIHandler.monitor") != null) { monitor = true; } boolean serviceUnavailable = isServiceUnavailable(properties); String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension"); HashMap serverVerbs = ServerVerb.getVerbs(properties); HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties); Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer"); boolean forceRender = false; if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) { forceRender = true; } request.setCharacterEncoding("UTF-8"); Date then = null; if (monitor) { then = new Date(); } if (debug) { Enumeration headerNames = request.getHeaderNames(); log.debug("OAIHandler.doGet: "); while (headerNames.hasMoreElements()) { String headerName = (String) headerNames.nextElement(); log.debug(headerName + ": " + request.getHeader(headerName)); } } if (serviceUnavailable) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Sorry. This server is down for maintenance"); } else { try { String userAgent = request.getHeader("User-Agent"); if (userAgent == null) { userAgent = ""; } else { userAgent = userAgent.toLowerCase(); } Transformer serverTransformer = null; if (transformer != null) { // return HTML if the client is an old browser if (forceRender || userAgent.indexOf("opera") != -1 || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1 /* && userAgent.indexOf("netscape/7") == -1 */) { serverTransformer = transformer; } } String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer, serverVerbs, extensionVerbs, extensionPath); Writer out = LexMLOAIHandler.getWriter(request, response); out.write(result); out.flush(); IOUtils.closeQuietly(out); } catch (FileNotFoundException e) { log.error("Falha no processamento.", e); response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } catch (Throwable e) { log.error("Falha no processamento.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } if (monitor) { StringBuffer reqUri = new StringBuffer(request.getRequestURI()); String queryString = request.getQueryString(); // d=789 if (queryString != null) { reqUri.append("?").append(queryString); } Runtime rt = Runtime.getRuntime(); log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime()) + "ms: " + reqUri.toString()); } }
From source file:org.apache.maven.doxia.linkcheck.DefaultLinkCheck.java
/** * Writes some memory data to the log (if debug enabled). *///from w w w. j a v a2s.co m private void displayMemoryConsumption() { if (LOG.isDebugEnabled()) { Runtime r = Runtime.getRuntime(); LOG.debug("Memory: " + (r.totalMemory() - r.freeMemory()) / MEG + "M/" + r.totalMemory() / MEG + "M"); } }
From source file:info.magnolia.cms.exchange.simple.SimpleExchangeServlet.java
/** * @param request// w ww . j a va 2s . c om * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String statusMessage = ""; String status = ""; try { validateRequest(request); initializeContext(request); applyLock(request); receive(request); // remove cached files if successful this.cacheManager.flushAll(); status = SimpleSyndicator.ACTIVATION_SUCCESSFUL; } catch (OutOfMemoryError e) { Runtime rt = Runtime.getRuntime(); log.error("---------\nOutOfMemoryError caught during activation. Total memory = " //$NON-NLS-1$ + rt.totalMemory() + ", free memory = " //$NON-NLS-1$ + rt.freeMemory() + "\n---------"); //$NON-NLS-1$ statusMessage = e.getMessage(); status = SimpleSyndicator.ACTIVATION_FAILED; } catch (PathNotFoundException e) { log.error(e.getMessage(), e); statusMessage = "Parent not found (not yet activated): " + e.getMessage(); status = SimpleSyndicator.ACTIVATION_FAILED; } catch (Throwable e) { log.error(e.getMessage(), e); statusMessage = e.getMessage(); status = SimpleSyndicator.ACTIVATION_FAILED; } finally { cleanUp(request); response.setHeader(SimpleSyndicator.ACTIVATION_ATTRIBUTE_STATUS, status); response.setHeader(SimpleSyndicator.ACTIVATION_ATTRIBUTE_MESSAGE, statusMessage); } }
From source file:spade.utility.BitcoinTools.java
public void writeBlocksToCSV(int startIndex, int endIndex) { // Block block, int lastBlockId int lastBlockId = -1; final BitcoinTools bitcoinTools = new BitcoinTools(); String pattern = "#.##"; DecimalFormat decimalFormat = new DecimalFormat(pattern); final ConcurrentHashMap<Integer, Block> blockMap = new ConcurrentHashMap<Integer, Block>(); final AtomicInteger currentBlock = new AtomicInteger(startIndex); final int stopIndex = endIndex; final int totalThreads = Runtime.getRuntime().availableProcessors(); class BlockFetcher implements Runnable { public void run() { while (true) { if (blockMap.size() > totalThreads * 5) { // max objects to hold in memory max 1 MB * totalThreads * factor try { Thread.sleep(100); continue; } catch (Exception exception) { }//from w w w . j a va 2 s.c o m } int blockToFetch = currentBlock.getAndIncrement(); try { blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch)); } catch (JSONException exception) { Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " has invalid json. Redownloading.", exception); try { blockMap.put(blockToFetch, bitcoinTools.getBlock(blockToFetch)); } catch (JSONException ex) { Bitcoin.log(Level.SEVERE, "Block " + blockToFetch + " couldn't be included in CSV.", ex); } } if (blockToFetch >= stopIndex) { break; } } } } ArrayList<Thread> workers = new ArrayList<Thread>(); for (int i = 0; i < totalThreads; i++) { Thread th = new Thread(new BlockFetcher()); workers.add(th); th.start(); } int percentageCompleted = 0; for (int i = startIndex; i < endIndex; i++) { try { Block block; while (!blockMap.containsKey(i)) { } block = blockMap.get(i); blockMap.remove(i); lastBlockId = writeBlockToCSV(block, lastBlockId); if ((((i - startIndex + 1) * 100) / (endIndex - startIndex)) > percentageCompleted) { Runtime rt = Runtime.getRuntime(); long totalMemory = rt.totalMemory() / 1024 / 1024; long freeMemory = rt.freeMemory() / 1024 / 1024; long usedMemory = totalMemory - freeMemory; System.out.print("| Cores: " + rt.availableProcessors() + " | Threads: " + totalThreads + " | Heap (MB) - total: " + totalMemory + ", %age free: " + (freeMemory * 100) / totalMemory + " | At Block: " + (i - startIndex + 1) + " / " + (endIndex - startIndex) + " | Percentage Completed: " + percentageCompleted // + " |\r"); + " |\n"); } percentageCompleted = ((i - startIndex + 1) * 100) / (endIndex - startIndex); } catch (IOException ex) { Bitcoin.log(Level.SEVERE, "Unexpected IOException. Stopping CSV creation.", ex); break; } } for (int i = 0; i < totalThreads; i++) { try { workers.get(i).interrupt(); workers.get(i).join(); } catch (InterruptedException exception) { } } System.out.println("\n\ndone with creating CSVes!"); }
From source file:ffx.Main.java
/** * Main does some window initializations. * * @param commandLineFile a {@link java.io.File} object. * @param argList a {@link java.util.List} object. *///w w w . j ava 2s.c om public Main(File commandLineFile, List<String> argList) { super("Force Field X"); // Start the clock. stopWatch.start(); setVisible(false); // Create the MainPanel and MainMenu, then add them to the JFrame java.awt.Toolkit.getDefaultToolkit().setDynamicLayout(true); mainPanel = new MainPanel(this); logHandler.setMainPanel(mainPanel); add(mainPanel); mainPanel.initialize(); setJMenuBar(mainPanel.getMainMenu()); // Set the Title and Icon setTitle("Force Field X"); URL iconURL = getClass().getClassLoader().getResource("ffx/ui/icons/icon64.png"); ImageIcon icon = new ImageIcon(iconURL); setIconImage(icon.getImage()); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (mainPanel != null) { mainPanel.exit(); } System.exit(0); } }); // This is a hack to get GraphicsCanvis to initialize on some // platform/Java3D combinations. mainPanel.setPanel(MainPanel.KEYWORDS); setVisible(true); mainPanel.setPanel(MainPanel.GRAPHICS); // Mac OS X specific features that help Force Field X look native // on Macs. This needs to be done after the MainPanel is created. if (SystemUtils.IS_OS_MAC_OSX) { osxAdapter = new OSXAdapter(mainPanel); } // Finally, open the supplied file if necessary. if (commandLineFile != null && !commandLineFile.exists()) { /** * See if the commandLineFile is an embedded script. */ String name = commandLineFile.getName(); name = name.replace('.', '/'); String pathName = "ffx/scripts/" + name; ClassLoader loader = getClass().getClassLoader(); URL embeddedScript = loader.getResource(pathName + ".ffx"); if (embeddedScript == null) { embeddedScript = loader.getResource(pathName + ".groovy"); } if (embeddedScript != null) { try { commandLineFile = new File(FFXClassLoader.copyInputStreamToTmpFile(embeddedScript.openStream(), commandLineFile.getName(), ".ffx")); } catch (Exception e) { logger.info(String.format(" The embedded script %s could not be extracted.", embeddedScript)); } } } if (commandLineFile != null) { if (commandLineFile.exists()) { mainPanel.getModelingShell().setArgList(argList); mainPanel.open(commandLineFile, null); } else { logger.warning(format("%s was not found.", commandLineFile.toString())); } } if (logger.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); sb.append(format("\n Start-up Time (msec): %s.", stopWatch.getTime())); Runtime runtime = Runtime.getRuntime(); runtime.runFinalization(); runtime.gc(); long occupiedMemory = runtime.totalMemory() - runtime.freeMemory(); long KB = 1024; sb.append(format("\n In-Use Memory (Kb): %d", occupiedMemory / KB)); sb.append(format("\n Free Memory (Kb): %d", runtime.freeMemory() / KB)); sb.append(format("\n Total Memory (Kb): %d", runtime.totalMemory() / KB)); logger.fine(sb.toString()); } }
From source file:at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.pipeline.consumer.impl.QuadtreeBuilderConsumer.java
@Override public void checkRuntimeMemory() { Runtime runtime = Runtime.getRuntime(); /** TOTAL MEMORY - FREE MEMORY > USED MEMORY */ long usedMemory = runtime.totalMemory() - runtime.freeMemory(); if (usedMemory > usedMemoryLimit) { /** If last memory check was performed less than 10 seconds ago, decrease minNumFeaturesLimiter */ if (new Date().getTime() - timeLastMemoryCheck < 1000 * 10) { minNumFeaturesLimiter++;/*from ww w. j av a2 s . c o m*/ if (minNumFeaturesLimiter > 4) minNumFeaturesLimiter = 4; } else { /** default values */ minNumFeaturesLimiter = 1; previousLimit = Integer.MAX_VALUE; timeLastMemoryCheck = new Date().getTime(); } int limit = 0; if (usedMemory > usedMemoryLimit + 1024 * 1024 * 1024) { limit = 0; } else if (usedMemory > usedMemoryLimit + 1024 * 1024 * 512) { limit = 36 / minNumFeaturesLimiter; } else if (usedMemory > usedMemoryLimit + 1024 * 1024 * 256) { limit = 360 / minNumFeaturesLimiter; } else if (usedMemory > usedMemoryLimit) { limit = 1800 / minNumFeaturesLimiter; } /** Only write file if current limit is lower than previous limit */ if (limit < previousLimit) { writePbfFile(limit); previousLimit = limit; } else { } } }
From source file:org.fcrepo.server.security.xacml.pdp.data.FedoraPolicyStore.java
@Override public void init() throws PolicyStoreException, FileNotFoundException { if (log.isDebugEnabled()) { Runtime runtime = Runtime.getRuntime(); log.debug("Total memory: " + runtime.totalMemory() / 1024); log.debug("Free memory: " + runtime.freeMemory() / 1024); log.debug("Max memory: " + runtime.maxMemory() / 1024); }/*from w ww .j a va 2 s. c o m*/ super.init(); // if no pid namespace was specified, use the default specified in fedora.fcfg if (pidNamespace.equals("")) { pidNamespace = fedoraServer.getModule("org.fcrepo.server.storage.DOManager") .getParameter("pidNamespace"); } // check control group was supplied if (datastreamControlGroup.equals("")) { throw new PolicyStoreException( "No control group for policy datastreams was specified in FedoraPolicyStore configuration"); } if (validateSchema) { String schemaLocation = schemaLocations.get(XACML20_POLICY_NS); if (schemaLocation == null) { throw new PolicyStoreException("Configuration error - no policy schema specified"); } try { String serverHome = fedoraServer.getHomeDir().getCanonicalPath() + File.separator; String schemaPath = ((schemaLocation).startsWith(File.separator) ? "" : serverHome) + schemaLocation; FileInputStream in = new FileInputStream(schemaPath); PolicyParser policyParser = new PolicyParser(in); ValidationUtility.setFeslPolicyParser(policyParser); } catch (IOException ioe) { throw new PolicyStoreException(ioe.getMessage(), ioe); } catch (SAXException se) { throw new PolicyStoreException(se.getMessage(), se); } } }
From source file:org.mrgeo.services.wms.WmsGenerator.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*from w w w . j a va2 s .c om*/ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final long start = System.currentTimeMillis(); try { log.debug("Semaphores available: {}", semaphore.availablePermits()); semaphore.acquire(); log.debug("Semaphore acquired. Semaphores available: {}", semaphore.availablePermits()); ServletUtils.printRequestURL(request); ServletUtils.printRequestAttributes(request); ServletUtils.printRequestParams(request); final String cache = ServletUtils.getParamValue(request, "cache"); if (!StringUtils.isEmpty(cache) && cache.toLowerCase().equals("off")) { response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); } else { response.setHeader("Cache-Control", "max-age=3600"); response.setHeader("Pragma", ""); response.setDateHeader("Expires", 3600); } String requestParam = ServletUtils.getParamValue(request, "request"); if (requestParam == null || requestParam.isEmpty()) { requestParam = "GetCapabilities"; } requestParam = requestParam.toLowerCase(); String serviceParam = ServletUtils.getParamValue(request, "service"); if (serviceParam == null || serviceParam.isEmpty()) { serviceParam = "wms"; } if (!serviceParam.toLowerCase().equals("wms")) { throw new Exception( "Invalid service type was requested. (only WMS is supported '" + serviceParam + "')"); } if (requestParam.equals("getmap") || requestParam.equals("getmosaic") || requestParam.equals("gettile")) { if (!requestParam.equals("gettile")) { ServletUtils.validateParam(request, "layers", "string"); } else { ServletUtils.validateParam(request, "layer", "string"); } ServletUtils.validateParam(request, "format", "string"); final String cs = ServletUtils.getParamValue(request, "crs"); if (!StringUtils.isEmpty(cs)) { if (!cs.toUpperCase().equals("CRS:84")) { throw new Exception("InvalidCRS: Invalid coordinate system \"" + cs + "\". Only coordinate system CRS:84 is supported."); } } OpImageRegistrar.registerMrGeoOps(); } // TODO: Need to construct provider properties from the WebRequest using // a new security layer and pass those properties to MapAlgebraJob. Properties providerProperties = SecurityUtils.getProviderProperties(); if (requestParam.equals("getcapabilities")) { getCapabilities(request, response, providerProperties); } else if (requestParam.equals("getmap")) { getMap(request, response, providerProperties); } else if (requestParam.equals("getmosaic")) { getMosaic(request, response, providerProperties); } else if (requestParam.equals("gettile")) { getTile(request, response, providerProperties); } else if (requestParam.equals("describetiles")) { describeTiles(request, response, providerProperties); } else { throw new Exception("Invalid request type made."); } } catch (final Exception e) { e.printStackTrace(); try { response.setContentType("text/xml"); writeError(e, response); } // we already started writing out to HTTP, instead return an error. catch (final Exception exception) { log.warn("Exception writing error: {}", exception); throw new IOException("Exception while writing XML exception (ah, the irony). " + "Original Exception is below." + exception.getLocalizedMessage(), e); } } finally { semaphore.release(); if (log.isDebugEnabled()) { log.debug("Semaphore released. Semaphores available: {}", semaphore.availablePermits()); 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:no.uio.medicine.virsurveillance.parsers.CSVsGBDdata.java
public void parse(String deathFolder) throws IOException { File f = new File(deathFolder); Runtime runtime = Runtime.getRuntime(); if (f.isDirectory()) { String[] filesInDir = f.list(); for (String fil : filesInDir) { if (fil.endsWith(".zip")) { ZipFile zipFile = new ZipFile(deathFolder + "/" + fil); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { System.out.println( "Used memory: " + (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024) + " Free memory: " + (runtime.freeMemory()) / (1024 * 1024)); ZipEntry entry = entries.nextElement(); InputStream stream = zipFile.getInputStream(entry); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); CSVParser parser = CSVFormat.RFC4180.withDelimiter(',').withIgnoreEmptyLines().withHeader() .parse(br);//from w w w . ja va 2s. c o m List<CSVRecord> records = parser.getRecords(); System.out.println("Reading records: " + zipFile.getName() + "/" + entry); /*for (int i=0;i<records.size();i++) { CSVRecord csvRecord = records.get(i);*/ for (CSVRecord csvRecord : records) { if (csvRecord.isMapped("age_group_id")) { //age group 22 corresponds to all ages if (csvRecord.get("age_group_id").equalsIgnoreCase("22")) { String location = null; String year = null; String sex = null; String cause = null; String number = null; String metric = null; if (csvRecord.isMapped("location_code")) { location = csvRecord.get("location_code"); } if (csvRecord.isMapped("year")) { year = csvRecord.get("year"); } if (csvRecord.isMapped("sex_id")) { //1=male, 2 = female if (csvRecord.get("sex_id").equalsIgnoreCase(("1"))) { sex = "m"; } else if (csvRecord.get("sex_id").equalsIgnoreCase("2")) { sex = "f"; } } if (csvRecord.isMapped("cause_name")) { cause = csvRecord.get("cause_name"); } if (csvRecord.isMapped("mean")) { number = csvRecord.get("mean"); } if (csvRecord.isMapped("metric") && csvRecord.isMapped("unit")) { metric = csvRecord.get("metric") + "-" + csvRecord.get("unit"); } if (location != null && year != null && sex != null && cause != null && number != null && metric != null) { try { sqlM.addSanitaryIssueToCountry(location, year, sex, cause, metric, number); } catch (SQLException ex) { Logger.getLogger(CSVsGBDdata.class.getName()).log(Level.SEVERE, null, ex); } } } } } parser.close(); stream.close(); br.close(); } zipFile.close(); } } } else { System.out.println("Not a directory"); } }
From source file:com.atlassian.jira.startup.JiraSystemInfo.java
/** * This only gets the most basic environment information to avoid bring up the JIRA world before the raw database * checks are done./*w ww . j av a 2s. c o m*/ * <p/> * It MUST BE CAREFUL not to access an JIRA code that will bring up the world * * @param context - a ServletContext that the app is running in. This may be nulll */ public void obtainBasicInfo(final ServletContext context) { final SystemInfoUtils systemInfoUtils = new SystemInfoUtilsImpl(); final ReleaseInfo releaseInfo = ReleaseInfo.getReleaseInfo(ReleaseInfo.class); logMsg.outputHeader("Environment"); logMsg.outputProperty("JIRA Build", buildUtilsInfo.getBuildInformation()); logMsg.outputProperty("Build Date", String.valueOf(buildUtilsInfo.getCurrentBuildDate())); logMsg.outputProperty("JIRA Installation Type", releaseInfo.getInfo()); if (context != null) { logMsg.outputProperty("Application Server", context.getServerInfo() + " - Servlet API " + context.getMajorVersion() + "." + context.getMinorVersion()); } logMsg.outputProperty("Java Version", jiraSystemProperties.getProperty("java.version", STRANGELY_UNKNOWN) + " - " + jiraSystemProperties.getProperty("java.vendor", STRANGELY_UNKNOWN)); logMsg.outputProperty("Current Working Directory", jiraSystemProperties.getProperty("user.dir", STRANGELY_UNKNOWN)); final Runtime rt = Runtime.getRuntime(); final long maxMemory = rt.maxMemory() / MEGABYTE; final long totalMemory = rt.totalMemory() / MEGABYTE; final long freeMemory = rt.freeMemory() / MEGABYTE; final long usedMemory = totalMemory - freeMemory; logMsg.outputProperty("Maximum Allowable Memory", maxMemory + "MB"); logMsg.outputProperty("Total Memory", totalMemory + "MB"); logMsg.outputProperty("Free Memory", freeMemory + "MB"); logMsg.outputProperty("Used Memory", usedMemory + "MB"); for (final MemoryInformation memory : systemInfoUtils.getMemoryPoolInformation()) { logMsg.outputProperty("Memory Pool: " + memory.getName(), memory.toString()); } logMsg.outputProperty("JVM Input Arguments", systemInfoUtils.getJvmInputArguments()); // do we have any patches Set<AppliedPatchInfo> appliedPatches = AppliedPatches.getAppliedPatches(); if (appliedPatches.size() > 0) { logMsg.outputHeader("Applied Patches"); for (AppliedPatchInfo appliedPatch : appliedPatches) { logMsg.outputProperty(appliedPatch.getIssueKey(), appliedPatch.getDescription()); } } logMsg.outputProperty("Java Compatibility Information", "JIRA version = " + buildUtilsInfo.getVersion() + ", Java Version = " + jiraSystemProperties.getProperty("java.version", STRANGELY_UNKNOWN)); }