1 package org.tanukisoftware.wrapper.test; 2 3 45 46 import java.io.FileWriter ; 47 import java.io.IOException ; 48 import java.io.Writer ; 49 import java.lang.reflect.InvocationTargetException ; 50 import java.lang.reflect.Method ; 51 52 57 public class Memory implements Runnable 58 { 59 private Writer m_writer; 60 private Thread m_runner; 61 62 65 public void run() 66 { 67 if ( m_runner == null ) 68 { 69 m_runner = Thread.currentThread(); 71 } 72 else 73 { 74 System.out.println("Stopping..." ); 75 m_runner = null; 77 return; 78 } 79 80 long startTime = System.currentTimeMillis(); 81 long lastTest = startTime; 82 try 83 { 84 m_writer.write( "--> Starting Memory Log\n" ); 85 m_writer.flush(); 86 87 while( m_runner != null ) 88 { 89 long now = System.currentTimeMillis(); 90 System.out.println( "Running for " + ( now - startTime ) + "ms..." ); 91 92 if ( now - lastTest > 15000 ) 93 { 94 Runtime rt = Runtime.getRuntime(); 95 System.gc(); 96 long totalMemory = rt.totalMemory(); 97 long freeMemory = rt.freeMemory(); 98 long usedMemory = totalMemory - freeMemory; 99 100 m_writer.write( "total memory=" + pad( totalMemory, 10 ) 101 + ", used=" + pad( usedMemory, 10 ) 102 + ", free=" + pad( freeMemory, 10 ) + "\n" ); 103 m_writer.flush(); 104 105 lastTest = now; 106 } 107 108 try 109 { 110 Thread.sleep( 250 ); 111 } 112 catch ( InterruptedException e ) 113 { 114 } 115 } 116 117 m_writer.write( "<-- Stopping Memory Log\n" ); 118 m_writer.flush(); 119 m_writer.close(); 120 } 121 catch ( IOException e ) 122 { 123 e.printStackTrace(); 124 } 125 } 126 127 130 private static final String PADDING = " "; 131 private String pad( long n, int len ) 132 { 133 String s = Long.toString( n ); 134 int sLen = s.length(); 135 if ( sLen < len ) 136 { 137 s = s + PADDING.substring( 0, len - sLen ); 138 } 139 return s; 140 } 141 144 public static void main(String [] args) 145 { 146 System.out.println("Memory Tester Running..."); 147 148 Method addShutdownHookMethod; 151 try { 152 addShutdownHookMethod = 153 Runtime .class.getMethod("addShutdownHook", new Class [] {Thread .class}); 154 } catch (NoSuchMethodException e) { 155 System.out.println("Shutdown hooks not supported by current JVM."); 156 addShutdownHookMethod = null; 157 } 158 159 Memory app = new Memory(); 160 161 try 163 { 164 app.m_writer = new FileWriter ( "memory.log" ); 165 } 166 catch ( IOException e ) 167 { 168 e.printStackTrace(); 169 return; 170 } 171 172 if (addShutdownHookMethod != null) { 174 Runtime runtime = Runtime.getRuntime(); 175 Thread hook = new Thread ( app, "shutdown-hook" ); 176 try { 177 addShutdownHookMethod.invoke(runtime, new Object [] {hook}); 178 } catch (IllegalAccessException e) { 179 System.out.println("Unable to register shutdown hook: " + e.getMessage()); 180 } catch (InvocationTargetException e) { 181 System.out.println("Unable to register shutdown hook: " + e.getMessage()); 182 } 183 } 184 185 new Thread ( app, "runner" ).start(); 187 } 188 } 189 | Popular Tags |