public static void main(String as[]) { Hello h = new Hello(); Hello h1 = new Hello(); Hello h2 = new Hello(); Hello h3 = new Hello(); System.runFinalization(); System.gc(); System.out.println("GC1"); h.m1(); h.m2(); Hai hai = new Hai(); hai = null; Hai hai1 = new Hai(); hai1 = hai; System.runFinalization(); System.gc(); /* A a=new A(); a.show(); System.runFinalization(); System.gc(); */ }
private Bench runBenchmark(Class<? extends Lookup> cls, int count) throws Exception { System.err.println("* Running " + count + " iterations for " + cls.getSimpleName() + " ..."); System.err.println(" - warm-up 10 iterations..."); for (int i = 0; i < 10; i++) { System.runFinalization(); System.gc(); Lookup lookup = cls.newInstance(); _benchmark(lookup, null, false, null); lookup = null; } Bench b = new Bench(); System.err.print(" - main iterations:"); System.err.flush(); for (int i = 0; i < count; i++) { System.runFinalization(); System.gc(); Lookup lookup = cls.newInstance(); _benchmark(lookup, null, false, b); lookup = null; if (i > 0 && (i % 10 == 0)) { System.err.print(" " + i); System.err.flush(); } } System.err.println(); return b; }
/** * Calculates (with varying degree of error) the memory used by a specific kind of object. It is * best to call this method multiple times to get an accurate reading. * * @param <E> the type of object * @param factory the object factory * @return the amount of memory (in bytes) one instance of a class uses */ public static <E> long calculateMemoryUsage(ObjectFactory<E> factory) { @SuppressWarnings("unused") // creating the first unused object pulls the class definition into memory if it already hasn't // been. E handle = factory.createObject(); long mem0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); long mem1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); handle = null; // basically force garbage collection to run System.runFinalization(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); mem0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); handle = factory.createObject(); System.runFinalization(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); System.gc(); mem1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); return mem1 - mem0; }
public void run() { // Listen for packets tracker.startReceive(System.currentTimeMillis()); try { runLoop(); } catch (Throwable t) { // Impossible? It keeps on exiting. We get the below, // but not this... try { System.err.print(t.getClass().getName()); System.err.println(); } catch (Throwable tt) { } ; try { System.err.print(t.getMessage()); System.err.println(); } catch (Throwable tt) { } ; try { System.gc(); System.runFinalization(); System.gc(); System.runFinalization(); } catch (Throwable tt) { } try { Runtime r = Runtime.getRuntime(); System.err.print(r.freeMemory()); System.err.println(); System.err.print(r.totalMemory()); System.err.println(); } catch (Throwable tt) { } ; try { t.printStackTrace(); } catch (Throwable tt) { } ; } finally { System.err.println("run() exiting for UdpSocketHandler on port " + _sock.getLocalPort()); Logger.error(this, "run() exiting for UdpSocketHandler on port " + _sock.getLocalPort()); synchronized (this) { _isDone = true; notifyAll(); } } }
void m2() { System.out.println("m2-begin"); System.runFinalization(); System.gc(); Hai hai = new Hai(); System.out.println("m1-end"); }
public static void main(String[] args) throws Exception { System.setSecurityManager(new SecurityManager()); // Create an uninitialized class loader try { new ClassLoader(null) { @Override protected void finalize() { loader = this; } }; } catch (SecurityException exc) { // Expected } System.gc(); System.runFinalization(); // if 'loader' isn't null, need to ensure that it can't be used as // parent if (loader != null) { try { // Create a class loader with 'loader' being the parent URLClassLoader child = URLClassLoader.newInstance(new URL[0], loader); throw new RuntimeException("Test Failed!"); } catch (SecurityException se) { System.out.println("Test Passed: Exception thrown"); } } else { System.out.println("Test Passed: Loader is null"); } }
/** * Returns an approximation of the amount of memory that is being used. * * <p>Not that this call might affecting timings. * * @return approximate # of bytes of memory used */ public static long getApproximateUsedMemory() { System.gc(); System.runFinalization(); final long totalMemory = Runtime.getRuntime().totalMemory(); final long free = Runtime.getRuntime().freeMemory(); return totalMemory - free; }
final synchronized void deconnection(String id) { for (Iterator i = distantKernels.iterator(); i.hasNext(); ) { AgentAddress distantK = (AgentAddress) i.next(); if (distantK.getKernel().getID().equals(id)) { debug("disconnected from " + id); for (Iterator j = organizations.entrySet().iterator(); j.hasNext(); ) { Map.Entry e = (Map.Entry) j.next(); Organization org = (Organization) e.getValue(); if (org.removeAgentsFromKernel(distantK.getKernel())) { leaveGroup("communities", (String) e.getKey()); sendAll( new SynchroMessage( Kernel.LEAVE_GROUP, getAddress(), COMMUNITIES, (String) e.getKey(), null, null)); sendAll(new SynchroMessage(Kernel.DELETE_COMMUNITY, (String) e.getKey())); j.remove(); } } kernelAgent.callHooks(Kernel.DISCONNECTED_FROM, distantK.getKernel()); kernelAgent.callHooks(Kernel.REMOVE_MEMBER_ROLE, distantK, COMMUNITIES, PUBLIC, SITE); i.remove(); System.gc(); System.runFinalization(); break; } } if (gui != null) gui.refreshCommunities(); }
@Override public void tearDown() throws Exception { for (Observer observer : observers) { observer.close(); } for (Participant participant : participants) { participant.stop(); } participants.clear(); assertFalse(failure); System.gc(); System.gc(); System.runFinalization(); System.runFinalization(); Thread.sleep(100); }
/** * Sends a leave message to the multicast group and leaves it. The <CODE>DiscoveryResponder</CODE> * leaves its multicast group. This method has no effect if the <CODE>DiscoveryResponder</CODE> is * <CODE>OFFLINE</CODE> or <CODE>STOPPING</CODE> or <CODE>STARTING</CODE>. */ public void stop() { if (state == ONLINE) { changeState(STOPPING); // ------------------------ // Stop corresponding thread // ------------------------ responder.stopRequested = true; synchronized (responder.interrupted) { if (!responder.interrupted.booleanValue()) { responderThread.interrupt(); } } // Fix for cases when the interrupt does not work (Windows NT) try { MulticastSocket ms = new MulticastSocket(multicastPort); // NPCTE fix for bugId 4499338, esc 0, 04 Sept 2001 if (usrInet != null) { ms.setInterface(usrInet); if (logger.finerOn()) { logger.finer("stop ", "use the interface " + usrInet); } } // end of NPCTE fix for bugId 4499338 InetAddress group = InetAddress.getByName(multicastGroup); ms.joinGroup(group); ms.send(new DatagramPacket(new byte[1], 1, group, multicastPort)); ms.leaveGroup(group); } catch (Exception e) { if (logger.finerOn()) { logger.finer( "stop ", "Unexpected exception occurred trying to send empty message " + e.getMessage()); } } // ------------------------ // free 'remained' allocated resource // ------------------------ responder = null; System.runFinalization(); // ---------------- // Update state // ---------------- // changeState(OFFLINE) ; } else { if (logger.finerOn()) { logger.finer("stop ", "Responder is not ONLINE"); } } }
/** Force system garbage collection. */ private void runGarbageCollection() { if (!disable_gc) { if (DEBUG_PRINT_MEM) { System.out.println("runGarbageCollection()"); } System.runFinalization(); System.gc(); } }
@SideEffect("Causes OutOfMemoryError to test finalization") public void test_get_SoftReference() { class TestObject { public boolean finalized; public TestObject() { finalized = false; } protected void finalize() { finalized = true; } } final ReferenceQueue rq = new ReferenceQueue(); class TestThread extends Thread { public void run() { Object testObj = new TestObject(); r = new SoftReference(testObj, rq); } } Reference ref; try { TestThread t = new TestThread(); t.start(); t.join(); Vector<StringBuffer> v = new Vector<StringBuffer>(); try { while (true) { v.add(new StringBuffer(10000)); } } catch (OutOfMemoryError ofme) { v = null; } } catch (InterruptedException e) { fail("InterruptedException : " + e.getMessage()); } assertNull("get() should return null " + "if OutOfMemoryError is thrown.", r.get()); try { TestThread t = new TestThread(); t.start(); t.join(); System.gc(); System.runFinalization(); ref = rq.poll(); assertNotNull("Object not garbage collected.", ref); assertNull("Object is not null.", ref.get()); assertNotNull("Object could not be reclaimed.", r.get()); } catch (Exception e) { fail("Exception : " + e.getMessage()); } }
public static void main(String[] args) { server = new HttpSolrServer(DEFAULT_URL); Random random = new Random(100); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43); readFileByLines(filename, analyzer, random); analyzer.close(); server = null; System.runFinalization(); System.gc(); }
@SuppressFBWarnings("DM_GC") // Used to trigger strictmode detecting leaked closeables @Override protected void tearDown() throws Exception { try { NativeTestServer.shutdownNativeTestServer(); mTestFramework.mCronetEngine.shutdown(); assertTrue(mFile.delete()); // Run GC and finalizers a few times to pick up leaked closeables for (int i = 0; i < 10; i++) { System.gc(); System.runFinalization(); } System.gc(); System.runFinalization(); super.tearDown(); } finally { StrictMode.setVmPolicy(mOldVmPolicy); } }
@After public void afterTest() { IoUtils.safeClose(clientChannel); IoUtils.safeClose(serverChannel); IoUtils.safeClose(connection); serviceRegistration.close(); System.gc(); System.runFinalization(); Logger.getLogger("TEST").infof("Finished test %s", name.getMethodName()); }
public final void init(final File dir) { this.dbExecutor.shutdownNow(); this.qExecutor.shutdown(); this.dbExecutor = Executors.newFixedThreadPool(3); this.qExecutor = Executors.newFixedThreadPool(2); System.runFinalization(); System.gc(); }
public static void main(String[] args) { String s = new String("helloworld"); ReferenceQueue rq = new ReferenceQueue(); PhantomReference pr = new PhantomReference(s, rq); s = null; System.out.println(pr.get()); // 系统无法通过虚引用来获得被引用的对象 System.gc(); System.runFinalization(); System.out.println(pr.get()); }
/** @param args */ public static void main(String[] args) { Trace.getInstance().addBaseClass("org.testium"); Trace.getInstance().addBaseClass("org.testtoolinterfaces"); RunTimeData rtData = new RunTimeData(); defineBaseDir(rtData); defineUserHome(rtData); defineStartTime(rtData); parseCommandLine(rtData, args); readGlobalConfigFile(rtData); readPersonalConfigFile(rtData); PluginCollection plugins = loadPlugins(rtData); Testium testium = createTestium(rtData, plugins); String command = rtData.getValueAsString(Testium.COMMAND); if (command.equalsIgnoreCase(CmdLineParser.VALIDATE)) { doValidation(testium, rtData); } else if (command.equalsIgnoreCase(CmdLineParser.EXECUTE)) { doExecution(testium, rtData); } else if (command.equalsIgnoreCase(CmdLineParser.PREPARE)) { doPreparations(testium, rtData); } else if (command.equalsIgnoreCase(CmdLineParser.INTERFACES)) { showInterfaces(plugins); } else if (command.equalsIgnoreCase(CmdLineParser.KEYWORDS)) { showKeywords(plugins); } else { throw new Error("Unknown Command: " + command); } System.out.flush(); System.err.flush(); // Find the root thread group ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); System.out.println("We start with threadgroup: " + root.getName()); while (root.getParent() != null) { root = root.getParent(); System.out.println("Up one to: " + root.getName()); } visit(root, 0); System.runFinalization(); try { Thread.sleep(30000); } catch (InterruptedException e) { // none, just exit; } System.exit(0); // Some plugins can have hanging threads. This will stop them. }
public static final void purgeMemory() { try { // Thread.sleep(50); System.runFinalization(); Thread.sleep(50); System.gc(); Thread.sleep(50); } catch (Throwable e) { Debug.debug(e); } }
public static void main(String[] args) { MyName obj1 = new MyName("인스턴스1"); MyName obj2 = new MyName("인스턴스2"); obj1 = null; obj2 = null; System.out.println("프로그램을 종료합니다."); // finalize()의 완벽한 호출을 위해 필요한 2개의 메소드 System.gc(); System.runFinalization(); }
private static void gc() { try { for (int i = 0; i < 2; i++) { System.gc(); Thread.sleep(100); System.runFinalization(); Thread.sleep(100); } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { String str = new String("Hello Java!"); ReferenceQueue<String> rq = new ReferenceQueue<String>(); // 創建一個虛引用,指向Hello Java! PhantomReference<String> pr = new PhantomReference<String>(str, rq); str = null; // 不能通過虛引用訪問被引用對象,所以此處為null System.out.println(pr.get()); System.gc(); System.runFinalization(); // 當被引用的對象回收后,虛引用將被放入引用隊列中 System.out.println(rq.poll() == pr); }
private static void gc() throws InterruptedException { ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>(); WeakReference<Object> weakReference = new WeakReference<Object>(new Object(), referenceQueue); while (weakReference.get() != null) { System.gc(); System.runFinalization(); } Assert.assertSame(weakReference, referenceQueue.remove()); }
final void handleConnectionMessage(ConnectionMessage m) { if (m.isTheFirstMessage()) { getCurrentKernel().synchronizeKernel(((ConnectionMessage) m).getOrgs(), true); establishConnectionWith(m.getSender(), false); } else getCurrentKernel().synchronizeKernel(((ConnectionMessage) m).getOrgs(), false); if (distantKernels.add(m.getSender())) { // System.out.println("Connecting to "+m.getSender()); kernelAgent.callHooks(Kernel.CONNECTED_TO, m.getSender().getKernel()); kernelAgent.callHooks(Kernel.ADD_MEMBER_ROLE, m.getSender(), COMMUNITIES, PUBLIC, SITE); } System.gc(); System.runFinalization(); }
/** Runs all JSR166 unit tests using junit.textui.TestRunner */ public static void main(String[] args) { int iters = 1; if (args.length > 0) iters = Integer.parseInt(args[0]); Test s = suite(); for (int i = 0; i < iters; ++i) { junit.textui.TestRunner.run(s); System.gc(); System.runFinalization(); } System.exit(0); }
// NOTE: this test relies on GC being actually done on the test object. // Java does not guarantee that to happen, so, if this test starts to fail // intermittently, feel free to comment it @Test public void testEventInjectionUnsubscribe() { IInjector injector = InjectorFactory.getDefault(); injector.addBinding(MyBinding.class); wrapSetup(); // do it in a separate method to ease GC System.gc(); System.runFinalization(); System.gc(); helper.sendEvent("e4/test/event1", "wrong"); assertFalse(testFailed); // target would have asserted if it is still // subscribed }
/** Un-hides the main menu and tries to clean up the client or server. */ void unlaunch() { // clean up server, if we have one if (server != null) { server.die(); server = null; } // show menu frame frame.setVisible(true); // just to free some memory client = null; System.gc(); System.runFinalization(); }
public static void testStrong() { // 字符串常量池共享(不能回收) String str = "BJ ni hao"; // 弱引用管理对象 WeakReference<String> wr = new WeakReference<String>(str); System.out.println("gc运行前:" + wr.get()); // 断开引用 str = null; // 通知回收 System.gc(); System.runFinalization(); System.out.println("gc运行后:" + wr.get()); }
// To be called exactly twice by the child process public static void rendezvousChild() { try { for (int i = 0; i < 100; i++) { System.gc(); System.runFinalization(); Thread.sleep(50); } System.out.write((byte) '\n'); System.out.flush(); System.in.read(); } catch (Throwable t) { throw new Error(t); } }
/** Do a reset of all cachers */ protected void doReset() { M_log.debug("doReset()"); final List<Ehcache> allCaches = getAllCaches(false); for (Ehcache ehcache : allCaches) { ehcache.removeAll(); // TODO should we doNotNotifyCacheReplicators? Ian? ehcache.clearStatistics(); } // run the garbage collector now System.runFinalization(); System.gc(); M_log.info("doReset(): Low Memory Recovery to: " + Runtime.getRuntime().freeMemory()); } // doReset