List of usage examples for java.lang Runtime totalMemory
public native long totalMemory();
From source file:org.openflamingo.web.util.VersionConfigurer.java
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { Log4jWebConfigurer.initLogging(servletContextEvent.getServletContext()); Properties properties = new Properties(); ServletContext context = servletContextEvent.getServletContext(); InputStream inputStream = null; try {/* w ww .j a v a 2s . c o m*/ inputStream = context.getResourceAsStream("/WEB-INF/version.properties"); properties.load(inputStream); } catch (Exception ex) { throw new IllegalArgumentException("Cannot load a '/WEB/INF/version.properties' file.", ex); } finally { IOUtils.closeQuietly(inputStream); } StringBuilder builder = new StringBuilder(); printHeader(builder, "Application Information"); Properties appProps = new Properties(); appProps.put("Application", "Flamingo Workflow Engine"); appProps.put("Version", properties.get("version")); appProps.put("Build Date", properties.get("build.timestamp")); appProps.put("Build Number", properties.get("build.number")); appProps.put("Revision Number", properties.get("revision.number")); appProps.put("Build Key", properties.get("build.key")); if (context != null) { appProps.put("Application Server", context.getServerInfo() + " - Servlet API " + context.getMajorVersion() + "." + context.getMinorVersion()); } Properties systemProperties = System.getProperties(); appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - " + systemProperties.getProperty("java.vendor", UNKNOWN)); appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN)); print(builder, appProps); Properties memPros = new Properties(); final Runtime rt = Runtime.getRuntime(); final long maxMemory = rt.maxMemory() / MEGA_BYTES; final long totalMemory = rt.totalMemory() / MEGA_BYTES; final long freeMemory = rt.freeMemory() / MEGA_BYTES; final long usedMemory = totalMemory - freeMemory; memPros.put("Maximum Allowable Memory", maxMemory + "MB"); memPros.put("Total Memory", totalMemory + "MB"); memPros.put("Free Memory", freeMemory + "MB"); memPros.put("Used Memory", usedMemory + "MB"); print(builder, memPros); printHeader(builder, "Java System Properties"); Properties sysProps = new Properties(); for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) { sysProps.put(entry.getKey(), entry.getValue()); } print(builder, sysProps); printHeader(builder, "System Environments"); Map<String, String> getenv = System.getenv(); Properties envProps = new Properties(); Set<String> strings = getenv.keySet(); for (String key : strings) { String message = getenv.get(key); envProps.put(key, message); } print(builder, envProps); logger.info("================================================="); logger.info(" Flamingo Web Services starting..."); logger.info("=================================================\n{}", builder.toString()); }
From source file:com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfigurationTest.java
private String getMemoryStats() { final Runtime rt = Runtime.getRuntime(); final long free = rt.freeMemory() / 1024; final long total = rt.totalMemory() / 1024; final long max = rt.maxMemory() / 1024; final long used = total - free; final String format = "used: {0,number,0}K, free: {1,number,0}K, total: {2,number,0}K, max: {3,number,0}K"; return MessageFormat.format(format, Long.valueOf(used), Long.valueOf(free), Long.valueOf(total), Long.valueOf(max));/*w w w. j av a 2s . c om*/ }
From source file:com.h3xstream.findbugs.test.BaseDetectorTest.java
@AfterClass public void after() { System.gc();// w w w .ja v a2 s . co m if (DEBUG) { Runtime rt = Runtime.getRuntime(); long inMb = 1024 * 1024; log.info("=== Memory info (Process " + ManagementFactory.getRuntimeMXBean().getName() + ") ==="); log.info("Total memory : " + rt.totalMemory() / inMb); log.info("Free memory : " + rt.freeMemory() / inMb); log.info("Memory usage : " + (rt.totalMemory() - rt.freeMemory()) / inMb); log.info("==================="); } // for(Object mock : mocksToReset) { // reset(mock); // } // mocksToReset.clear(); }
From source file:org.exem.flamingo.web.util.ApplicationInformationDisplayContextListener.java
@Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.setProperty("PID", SystemUtils.getPid()); Properties properties = new Properties(); ServletContext context = servletContextEvent.getServletContext(); InputStream inputStream = null; try {//from w w w . ja va 2 s. c o m inputStream = context.getResourceAsStream("/WEB-INF/app.properties"); properties.load(inputStream); } catch (Exception ex) { throw new IllegalArgumentException("Cannot load a '/WEB/INF/app.properties' file.", ex); } finally { IOUtils.closeQuietly(inputStream); } // See : http://patorjk.com/software/taag/#p=display&f=Slant&t=Flamingo StringBuilder builder = new StringBuilder(); builder.append(" ________ _ \n" + " / ____/ /___ _____ ___ (_)___ ____ _____ \n" + " / /_ / / __ `/ __ `__ \\/ / __ \\/ __ `/ __ \\\n" + " / __/ / / /_/ / / / / / / / / / / /_/ / /_/ /\n" + "/_/ /_/\\__,_/_/ /_/ /_/_/_/ /_/\\__, /\\____/ \n" + " /____/ "); printHeader(builder, "Application Information"); Properties appProps = new Properties(); appProps.put("Instance", StringUtils.isEmpty(System.getProperty("instance")) ? "** UNKNOWN **" : System.getProperty("instance")); appProps.put("Version", properties.get("version")); appProps.put("Build Date", properties.get("build.timestamp")); appProps.put("Build Number", properties.get("build.number")); appProps.put("Revision Number", properties.get("revision.number")); appProps.put("Organization", properties.get("organization")); appProps.put("Homepage", properties.get("homepage")); if (context != null) { appProps.put("Application Server", context.getServerInfo() + " - Servlet API " + context.getMajorVersion() + "." + context.getMinorVersion()); } Properties systemProperties = System.getProperties(); appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - " + systemProperties.getProperty("java.vendor", UNKNOWN)); appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN)); print(builder, appProps); Properties memPros = new Properties(); final Runtime rt = Runtime.getRuntime(); final long maxMemory = rt.maxMemory() / MEGA_BYTES; final long totalMemory = rt.totalMemory() / MEGA_BYTES; final long freeMemory = rt.freeMemory() / MEGA_BYTES; final long usedMemory = totalMemory - freeMemory; memPros.put("Maximum Allowable Memory", maxMemory + "MB"); memPros.put("Total Memory", totalMemory + "MB"); memPros.put("Free Memory", freeMemory + "MB"); memPros.put("Used Memory", usedMemory + "MB"); print(builder, memPros); printHeader(builder, "Java System Properties"); Properties sysProps = new Properties(); for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) { sysProps.put(entry.getKey(), entry.getValue()); } print(builder, sysProps); printHeader(builder, "System Environments"); Map<String, String> envs = System.getenv(); Properties envProps = new Properties(); Set<String> strings = envs.keySet(); for (String key : strings) { String message = envs.get(key); envProps.put(key, message); } print(builder, envProps); WebLogbackConfigurer.initLogging(servletContextEvent.getServletContext()); System.out.println(builder.toString()); logger.info("============================================================"); logger.info(" Now starting ..... PID: " + SystemUtils.getPid()); logger.info("============================================================"); }
From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java
public void testToJsonOnInheritedClassOutput() throws Exception { SpecialPerson[] spa = new SpecialPerson[TEST_SIZE]; for (int i = 0; i < TEST_SIZE; i++) { spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense"); }// w ww . j a v a2s . co m Runtime r = Runtime.getRuntime(); String[] output = new String[TEST_SIZE]; r.gc(); long memstart = r.totalMemory() - r.freeMemory(); long startOutput = System.currentTimeMillis(); for (int i = 0; i < TEST_SIZE; i++) { output[i] = ((JSONObject) beanJsonConverter.convertToJson(spa[i])).toString(); } long endOutput = System.currentTimeMillis(); long memend = r.totalMemory() - r.freeMemory(); String[] serializeOutput = new String[TEST_SIZE]; char[] source = output[0].toCharArray(); r.gc(); long stringsizeStart = r.totalMemory() - r.freeMemory(); for (int i = 0; i < TEST_SIZE; i++) { serializeOutput[i] = new String(source); } long stringsizeEnd = r.totalMemory() - r.freeMemory(); log.info("ORG JSON Lib Output " + average(startOutput, endOutput, TEST_SIZE) + " ms/conversion, " + (average(memstart, memend, TEST_SIZE) - average(stringsizeStart, stringsizeEnd, TEST_SIZE)) + " heap bytes/conversion, output packet consumed on average " + average(stringsizeStart, stringsizeEnd, TEST_SIZE) + " for a string length of " + output[0].length()); log.info("Output Was [" + output[0] + ']'); }
From source file:com.ibm.bluemix.mobilestarterkit.service.ServiceAPI.java
@Path("/autoscaling") @POST// w w w .j a v a2 s . com public String autoScalingByMem(String param) { try { JSONObject meta = new JSONObject(param); Runtime rt = Runtime.getRuntime(); int mem_usage = (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0)); String action = meta.getString("action"); if ("mem_up".equalsIgnoreCase(action)) { // 10M . Out of memory ? ?. for (int i = 0; i < 10; i++) { byte b[] = new byte[1048576]; v.add(b); } } else if ("mem_safe_up".equalsIgnoreCase(action) && mem_usage < 90) { // 90% ? ?, 10M . OOM for (int i = 0; i < 10; i++) { byte b[] = new byte[1048576]; v.add(b); } } else if ("mem_reset".equalsIgnoreCase(action)) { // ? v = new Vector(); rt.gc(); } String msg = "Max " + (rt.maxMemory() / 1000) + " KB Total used : " + (rt.totalMemory() / 1000) + " KB Free : " + (rt.freeMemory() / 1000) + " KB " + (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0)) + " %"; System.out.println(msg); return msg; } catch (JSONException e) { e.getStackTrace(); return "Failed"; } }
From source file:hydrograph.ui.joblogger.JobLogger.java
/** * //from w w w .ja va2s . c o m * Logs runtime properties * * @param jobLogger */ private void logRuntimeInformation(AbstractJobLogger jobLogger) { Runtime runtime = Runtime.getRuntime(); long maxMemory = runtime.maxMemory(); jobLogger.logWithNoTimeStamp("Max Memory: " + Long.toString(maxMemory / 1024)); long allocatedMemory = runtime.totalMemory(); jobLogger.logWithNoTimeStamp("Allocated Memory: " + Long.toString(allocatedMemory / 1024)); long freeMemory = runtime.freeMemory(); jobLogger.logWithNoTimeStamp("Free Memory: " + Long.toString(freeMemory / 1024)); jobLogger.logWithNoTimeStamp( "Total free memory: " + Long.toString((freeMemory + (maxMemory - allocatedMemory)) / 1024)); long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); jobLogger.logWithNoTimeStamp("Used Memory : " + Long.toString(used)); }
From source file:com.ettrema.zsync.IntegrationTests.java
/** * Creates the zsync File for servercopy, and saves it to a File with name fileName * @param fileName The name of the file in which to save the zsync data * @param blocksize The block size to use in MetaFileMaker * @return The created zsync File/*from www . ja v a 2 s . c om*/ * @throws FileNotFoundException */ private File createMetaFile(String fileName, int blocksize, File serverFile) throws FileNotFoundException { System.out.println("---------------- createMetaFile -------------------"); System.gc(); Runtime rt = Runtime.getRuntime(); startUsed = rt.totalMemory() - rt.freeMemory(); MetaFileMaker mkr = new MetaFileMaker(); File zsfile = mkr.make(null, blocksize, serverFile); System.gc(); System.out.println("Memory stats: " + formatBytes(rt.maxMemory()) + " - " + formatBytes(rt.totalMemory()) + " - " + formatBytes(rt.freeMemory())); long endUsed = (rt.totalMemory() - rt.freeMemory()); System.out.println("Start used memory: " + formatBytes(startUsed) + " end used memory: " + formatBytes(endUsed) + " - delta: " + formatBytes(endUsed - startUsed)); File dest = new File(filepath + fileName); if (dest.exists()) { if (!dest.delete()) { throw new RuntimeException("Failed to delete previous meta file: " + dest.getAbsolutePath()); } } System.out.println("rename meta file to: " + dest.getAbsolutePath()); if (!zsfile.renameTo(dest)) { throw new RuntimeException("Failed to rename to: " + dest.getAbsolutePath()); } System.out.println("Created meta file of size: " + formatBytes(dest.length()) + " from source file of size: " + formatBytes(serverFile.length())); System.out.println(""); return dest; }
From source file:org.openflamingo.engine.util.VersionConfigurer.java
/** * Notification that the web application initialization * process is starting.//from w ww . java 2 s . c o m * All ServletContextListeners are notified of context * initialization before any filter or servlet in the web * application is initialized. * * @param servletContextEvent {@link javax.servlet.ServletContextEvent} */ @Override public void contextInitialized(ServletContextEvent servletContextEvent) { Log4jWebConfigurer.initLogging(servletContextEvent.getServletContext()); Properties properties = new Properties(); ServletContext context = servletContextEvent.getServletContext(); InputStream inputStream = null; try { inputStream = context.getResourceAsStream("/WEB-INF/version.properties"); properties.load(inputStream); } catch (Exception ex) { throw new IllegalArgumentException("Cannot load a '/WEB/INF/version.properties' file.", ex); } finally { IOUtils.closeQuietly(inputStream); } StringBuilder builder = new StringBuilder(); printHeader(builder, "Application Information"); Properties appProps = new Properties(); appProps.put("Application", "Flamingo Workflow Engine"); appProps.put("Version", properties.get("version")); appProps.put("Build Date", properties.get("build.timestamp")); appProps.put("Build Number", properties.get("build.number")); appProps.put("Revision Number", properties.get("revision.number")); appProps.put("Build Key", properties.get("build.key")); if (context != null) { appProps.put("Application Server", context.getServerInfo() + " - Servlet API " + context.getMajorVersion() + "." + context.getMinorVersion()); } Properties systemProperties = System.getProperties(); appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - " + systemProperties.getProperty("java.vendor", UNKNOWN)); appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN)); print(builder, appProps); printHeader(builder, "JVM Heap Information"); Properties memPros = new Properties(); final Runtime rt = Runtime.getRuntime(); final long maxMemory = rt.maxMemory() / MEGA_BYTES; final long totalMemory = rt.totalMemory() / MEGA_BYTES; final long freeMemory = rt.freeMemory() / MEGA_BYTES; final long usedMemory = totalMemory - freeMemory; memPros.put("Maximum Allowable Memory", maxMemory + "MB"); memPros.put("Total Memory", totalMemory + "MB"); memPros.put("Free Memory", freeMemory + "MB"); memPros.put("Used Memory", usedMemory + "MB"); print(builder, memPros); printHeader(builder, "Java System Properties"); Properties sysProps = new Properties(); for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) { sysProps.put(entry.getKey(), entry.getValue()); } print(builder, sysProps); printHeader(builder, "System Environments"); Map<String, String> getenv = System.getenv(); Properties envProps = new Properties(); Set<String> strings = getenv.keySet(); for (String key : strings) { String message = getenv.get(key); envProps.put(key, message); } print(builder, envProps); logger.info("================================================="); logger.info(" Flamingo Workflow Engine starting..."); logger.info("=================================================\n{}", builder.toString()); }
From source file:spade.storage.Neo4j.java
public static void index(String dbpath, boolean printProgress) { int totalThreads = Runtime.getRuntime().availableProcessors(); final ConcurrentLinkedQueue<Node> nodeTaskQueue = new ConcurrentLinkedQueue<Node>(); final ConcurrentLinkedQueue<Relationship> edgeTaskQueue = new ConcurrentLinkedQueue<Relationship>(); final ReentrantReadWriteLock nodeRwlock = new ReentrantReadWriteLock(); final ReentrantReadWriteLock edgeRwlock = new ReentrantReadWriteLock(); final Index<Node> vertexIndex; final RelationshipIndex edgeIndex; System.out.println("Loading database..."); File databaseFile = new File(dbpath); final GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(databaseFile) .setConfig(GraphDatabaseSettings.pagecache_memory, "" + (Runtime.getRuntime().totalMemory() * 9) / 10) // .setConfig(GraphDatabaseSettings.keep_logical_logs, "false") .newGraphDatabase();//from w ww. j ava 2 s. c o m System.out.println("Loaded"); // clear already present indexes try (Transaction tx = graphDb.beginTx()) { graphDb.index().forNodes(spade.storage.Neo4j.VERTEX_INDEX).delete(); tx.success(); } try (Transaction tx = graphDb.beginTx()) { graphDb.index().forRelationships(spade.storage.Neo4j.EDGE_INDEX).delete(); tx.success(); } // System.out.println("Creating Indexing discriptors..."); try (Transaction tx = graphDb.beginTx()) { vertexIndex = graphDb.index().forNodes(spade.storage.Neo4j.VERTEX_INDEX); tx.success(); } try (Transaction tx = graphDb.beginTx()) { edgeIndex = graphDb.index().forRelationships(spade.storage.Neo4j.EDGE_INDEX); tx.success(); } System.out.println("Created"); class NodeIndexer implements Runnable { public void run() { Transaction tx = graphDb.beginTx(); int counter = 0; try { while (!Thread.currentThread().isInterrupted()) { if (counter < 10000) { Node node = nodeTaskQueue.poll(); if (node == null) { continue; } for (String key : node.getPropertyKeys()) { vertexIndex.add(node, key, (String) node.getProperty(key)); } node.setProperty(ID_STRING, node.getId()); vertexIndex.add(node, ID_STRING, Long.toString(node.getId())); counter++; } if (counter > 1000 && nodeRwlock.writeLock().tryLock()) { tx.success(); tx.close(); tx = graphDb.beginTx(); nodeRwlock.writeLock().unlock(); counter = 0; } } } finally { // tx.success(); tx.close(); if (nodeRwlock.writeLock().isHeldByCurrentThread()) { nodeRwlock.writeLock().unlock(); } } } } class RelationshipIndexer implements Runnable { public void run() { Transaction tx = graphDb.beginTx(); int counter = 0; try { while (!Thread.currentThread().isInterrupted()) { if (counter < 10000) { Relationship relationship = edgeTaskQueue.poll(); if (relationship == null) { continue; } for (String key : relationship.getPropertyKeys()) { edgeIndex.add(relationship, key, (String) relationship.getProperty(key)); } relationship.setProperty(ID_STRING, relationship.getId()); edgeIndex.add(relationship, ID_STRING, Long.toString(relationship.getId())); counter++; } if (counter > 1000 && edgeRwlock.writeLock().tryLock()) { // tx.success(); tx.close(); tx = graphDb.beginTx(); edgeRwlock.writeLock().unlock(); counter = 0; } } } finally { // tx.success(); tx.close(); if (edgeRwlock.writeLock().isHeldByCurrentThread()) { edgeRwlock.writeLock().unlock(); } } } } ArrayList<Thread> nodeWorkers = new ArrayList<Thread>(); for (int i = 0; i < totalThreads / 2; i++) { Thread th = new Thread(new NodeIndexer()); nodeWorkers.add(th); th.start(); } ArrayList<Thread> edgeWorkers = new ArrayList<Thread>(); for (int i = 0; i < totalThreads / 2; i++) { Thread th = new Thread(new RelationshipIndexer()); edgeWorkers.add(th); th.start(); } System.out.println("Counted Nodes and Relationships to index..."); final long total; try (Transaction tx = graphDb.beginTx()) { total = Iterators.count(graphDb.getAllNodes().iterator()) + Iterators.count(graphDb.getAllRelationships().iterator()); tx.success(); } System.out.println("done.\n"); long percentageCompleted = 0; int count = 0; try (Transaction tx = graphDb.beginTx()) { // index nodes Iterator<Node> nodeIterator = graphDb.getAllNodes().iterator(); Iterator<Relationship> edgeIterator = graphDb.getAllRelationships().iterator(); while (edgeIterator.hasNext() || nodeIterator.hasNext()) { if (nodeIterator.hasNext() && nodeTaskQueue.size() < 10000) { nodeTaskQueue.add(nodeIterator.next()); count = count + 1; } if (edgeIterator.hasNext() && edgeTaskQueue.size() < 10000) { edgeTaskQueue.add(edgeIterator.next()); count = count + 1; } if (printProgress) { if (((count * 100) / total) > 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 + " , " + (freeMemory * 100) / totalMemory + "% free" // + " | Total Objects (nodes + relationships) to Index: " + total + " | Indexing Object (nodes + relationships): " + count + " / " + total + " | Completed: " + percentageCompleted + " %" + " |\r"); } percentageCompleted = (count * 100) / total; } } tx.success(); } System.out.println("\n\nIndexing completed. Waiting for queues to clear..."); try { while (nodeTaskQueue.size() != 0 || edgeTaskQueue.size() != 0) { Thread.sleep(1000); } } catch (InterruptedException exception) { } System.out.println("Queues cleared. Threads teardown started..."); for (int i = 0; i < totalThreads / 2; i++) { nodeWorkers.get(i).interrupt(); try { nodeWorkers.get(i).join(); } catch (InterruptedException exception) { } } for (int i = 0; i < totalThreads / 2; i++) { edgeWorkers.get(i).interrupt(); try { edgeWorkers.get(i).join(); } catch (InterruptedException exception) { } } System.out.println("Database shutdown started..."); graphDb.shutdown(); }