Example usage for java.lang System runFinalization

List of usage examples for java.lang System runFinalization

Introduction

In this page you can find the example usage for java.lang System runFinalization.

Prototype

public static void runFinalization() 

Source Link

Document

Runs the finalization methods of any objects pending finalization.

Usage

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

/**
 * If subclasses overide they *must* call super.tearDown() first.
 *//*from  w  w w .java  2s . co m*/
@Override
protected void oneTimeTearDown() throws Exception {
    if (getTestData().isTestDataAvailable()) {
        try {
            //dispose WFS XSD schema's - they will otherwise keep geoserver instance alive forever!!
            disposeIfExists(getXSD11());
            disposeIfExists(getXSD10());

            // kill the context
            applicationContext.destroy();

            // kill static caches
            new GeoServerExtensions().setApplicationContext(null);

            // some tests do need a kick on the GC to fully clean up
            if (isMemoryCleanRequired()) {
                System.gc();
                System.runFinalization();
            }

            if (getTestData() != null) {
                // this cleans up the data directory static loader, if we don't the next test
                // will keep on running on the current data dir
                GeoserverDataDirectory.destroy();
                getTestData().tearDown();
            }
        } finally {
            applicationContext = null;
            testData = null;
        }
    }
}

From source file:org.xwoot.wootEngine.ContentManager.java

/**
 * Serializes the {@link WootContent}./*from   w w  w  .  j a va2 s  . com*/
 * 
 * @param wootFile the file to serialize.
 * @throws WootEngineException if serialization or file access problems occur.
 */
private void storeFile(WootFile wootFile) throws WootEngineException {
    String pageFilePath = this.getContentsDirPath() + File.separator + wootFile.getFileName();

    try {
        PersistencyUtil.saveObjectToXml(wootFile, pageFilePath);
    } catch (Exception e) {
        this.throwLoggedException("Problems storing page " + wootFile.getPageName());
    }
    System.runFinalization();
    System.gc();
}

From source file:fuse4j.hadoopfs.FuseHdfsClient.java

public int release(String path, Object fh, int flags) throws FuseException {
    log.info("release(): " + path + " flags: " + flags + "\n");
    unpinFileContext(path);//from  w  w w .j av  a2 s. c  o  m
    System.runFinalization();

    return 0;
}

From source file:org.kiji.schema.testutil.AbstractKijiIntegrationTest.java

@After
public final void teardownKijiIntegrationTest() throws Exception {
    // Schedule the Kiji instance for asynchronous deletion.
    if (CLEANUP_AFTER_TEST && (null != mKijiURI)) {
        mDeletionThread.destroyKiji(mKijiURI);
    }//  ww  w. j a  v a 2 s  . c  om

    mHelper = null;
    mKijiURI = null;
    mConf = null;

    // Force garbage collection:
    System.gc();
    System.runFinalization();
}

From source file:com.github.hexocraft.worldrestorer.WorldRestorerApi.java

private static boolean saveWorld(World world) {
    // Try to save all chunks
    final Chunk[] chunks = world.getLoadedChunks();
    for (final Chunk chunk : chunks)
        NmsWorldUtil.saveChunk(world, chunk);

    // Time reference
    long reference = new Date().getTime();

    // Save the world
    world.save();/*from   w  w w .j a va  2s . c o m*/

    // Wait for world to save
    try {
        long delay = 100, count = 0;
        while (count < 100) {
            long lastModify = new File(world.getWorldFolder(), "level.dat").lastModified();

            // Wait for the file to close
            if (lastModify - reference > 0) {
                Thread.sleep(800);
                return true;
            }

            // Wait again
            Thread.sleep(delay);

            // D'ont wait to much
            count++;
        }
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }

    System.runFinalization();
    System.gc();

    return false;
}

From source file:org.geoserver.GeoserverInitStartupListener.java

/**
 * This method tries hard to stop all threads and remove all references to classes in GeoServer
 * so that we can avoid permgen leaks on application undeploy.
 * What happes is that, if any JDK class references to one of the classes loaded by the
 * webapp classloader, then the classloader cannot be collected and neither can all the
 * classes loaded by it (since each class keeps a back reference to the classloader that
 * loaded it). The same happens for any residual thread launched by the web app.
 *///from  w w w.ja  v  a  2 s . co  m
public void contextDestroyed(ServletContextEvent sce) {
    try {
        LOGGER.info("Beginning GeoServer cleanup sequence");

        // the dreaded classloader
        ClassLoader webappClassLoader = getClass().getClassLoader();

        // unload all of the jdbc drivers we have loaded. We need to store them and unregister
        // later to avoid concurrent modification exceptions
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Set<Driver> driversToUnload = new HashSet<Driver>();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                // the driver class loader can be null if the driver comes from the JDK, such as the 
                // sun.jdbc.odbc.JdbcOdbcDriver
                ClassLoader driverClassLoader = driver.getClass().getClassLoader();
                if (driverClassLoader != null && webappClassLoader.equals(driverClassLoader)) {
                    driversToUnload.add(driver);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
        for (Driver driver : driversToUnload) {
            try {
                DriverManager.deregisterDriver(driver);
                LOGGER.info("Unregistered JDBC driver " + driver);
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Could now unload driver " + driver.getClass(), e);
            }
        }
        drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
        }
        try {
            Class h2Driver = Class.forName("org.h2.Driver");
            Method m = h2Driver.getMethod("unload");
            m.invoke(null);
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to unload the H2 driver", e);
        }

        // unload all deferred authority factories so that we get rid of the timer tasks in them
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCoordinateOperationAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCRSAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCSAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }

        // kill the threads created by referencing
        WeakCollectionCleaner.DEFAULT.exit();
        DeferredAuthorityFactory.exit();
        CRS.reset("all");
        LOGGER.info("Shut down GT referencing threads ");
        // reset 
        ReferencingFactoryFinder.reset();
        CommonFactoryFinder.reset();
        DataStoreFinder.reset();
        DataAccessFinder.reset();
        LOGGER.info("Shut down GT  SPI ");

        LOGGER.info("Shut down coverage thread pool ");
        Object o = Hints.getSystemDefault(Hints.EXECUTOR_SERVICE);
        if (o != null && o instanceof ExecutorService) {
            final ThreadPoolExecutor executor = (ThreadPoolExecutor) o;
            try {
                executor.shutdown();
            } finally {
                try {
                    executor.shutdownNow();
                } finally {

                }
            }
        }

        // unload everything that JAI ImageIO can still refer to
        // We need to store them and unregister later to avoid concurrent modification exceptions
        final IIORegistry ioRegistry = IIORegistry.getDefaultInstance();
        Set<IIOServiceProvider> providersToUnload = new HashSet();
        for (Iterator<Class<?>> cats = ioRegistry.getCategories(); cats.hasNext();) {
            Class<?> category = cats.next();
            for (Iterator it = ioRegistry.getServiceProviders(category, false); it.hasNext();) {
                final IIOServiceProvider provider = (IIOServiceProvider) it.next();
                if (webappClassLoader.equals(provider.getClass().getClassLoader())) {
                    providersToUnload.add(provider);
                }
            }
        }
        for (IIOServiceProvider provider : providersToUnload) {
            ioRegistry.deregisterServiceProvider(provider);
            LOGGER.info("Unregistering Image I/O provider " + provider);
        }

        // unload everything that JAI can still refer to
        final OperationRegistry opRegistry = JAI.getDefaultInstance().getOperationRegistry();
        for (String mode : RegistryMode.getModeNames()) {
            for (Iterator descriptors = opRegistry.getDescriptors(mode).iterator(); descriptors != null
                    && descriptors.hasNext();) {
                RegistryElementDescriptor red = (RegistryElementDescriptor) descriptors.next();
                int factoryCount = 0;
                int unregisteredCount = 0;
                // look for all the factories for that operation
                for (Iterator factories = opRegistry.getFactoryIterator(mode, red.getName()); factories != null
                        && factories.hasNext();) {
                    Object factory = factories.next();
                    if (factory == null) {
                        continue;
                    }
                    factoryCount++;
                    if (webappClassLoader.equals(factory.getClass().getClassLoader())) {
                        boolean unregistered = false;
                        // we need to scan against all "products" to unregister the factory
                        Vector orderedProductList = opRegistry.getOrderedProductList(mode, red.getName());
                        if (orderedProductList != null) {
                            for (Iterator products = orderedProductList.iterator(); products != null
                                    && products.hasNext();) {
                                String product = (String) products.next();
                                try {
                                    opRegistry.unregisterFactory(mode, red.getName(), product, factory);
                                    LOGGER.info("Unregistering JAI factory " + factory.getClass());
                                } catch (Throwable t) {
                                    // may fail due to the factory not being registered against that product
                                }
                            }
                        }
                        if (unregistered) {
                            unregisteredCount++;
                        }

                    }
                }

                // if all the factories were unregistered, get rid of the descriptor as well
                if (factoryCount > 0 && unregisteredCount == factoryCount) {
                    opRegistry.unregisterDescriptor(red);
                }
            }
        }

        // flush all javabean introspection caches as this too can keep a webapp classloader from being unloaded
        Introspector.flushCaches();
        LOGGER.info("Cleaned up javabean caches");

        // unload the logging framework
        if (!relinquishLoggingControl)
            LogManager.shutdown();
        LogFactory.release(Thread.currentThread().getContextClassLoader());

        // GeoTools/GeoServer have a lot of finalizers and until they are run the JVM
        // itself wil keepup the class loader...
        try {
            System.gc();
            System.runFinalization();
            System.gc();
            System.runFinalization();
            System.gc();
            System.runFinalization();
        } catch (Throwable t) {
            System.out.println("Failed to perform closing up finalization");
            t.printStackTrace();
        }
    } catch (Throwable t) {
        // if anything goes south during the cleanup procedures I want to know what it is
        t.printStackTrace();
    }
}

From source file:org.glom.web.server.libglom.DocumentTest.java

@Test
public void testGetSuitableTableToViewDetails() {

    // Create a new document for the film manager
    final Document filmManagerDocument = new Document();
    filmManagerDocument.setFileURI(testUriFilmManager);
    final boolean retval = filmManagerDocument.load();
    assertTrue(retval);/*w  w  w .jav  a2  s.c om*/

    // Get the "Scene Cast" related list portal. This relies on specific details of the film manager details
    // view layout. I've included safety checks that will fail if the layout changes.
    final List<LayoutGroup> detailsLayout = filmManagerDocument
            .getDataLayoutGroups(Document.LAYOUT_NAME_DETAILS, "scenes");
    assertEquals(3, detailsLayout.size());

    LayoutGroup layoutGroup = detailsLayout.get(1);
    assertEquals(Document.LAYOUT_NAME_DETAILS, layoutGroup.getName());
    assertEquals("Details", layoutGroup.getTitle(defaultLocale));
    assertEquals("Details", layoutGroup.getTitle(germanLocale));

    layoutGroup = detailsLayout.get(2);
    assertEquals("details_lower", layoutGroup.getName());

    List<LayoutItem> items = layoutGroup.getItems();
    assertEquals(2, items.size());

    final LayoutItem notebookItem = items.get(0);
    assertEquals("notebook", notebookItem.getName());
    assertTrue(notebookItem instanceof LayoutItemNotebook);
    final LayoutItemNotebook notebook = (LayoutItemNotebook) notebookItem;
    items = notebook.getItems();
    assertEquals(7, items.size());
    final LayoutItem portalItem = items.get(0);
    assertTrue(portalItem instanceof LayoutItemPortal);
    final LayoutItemPortal portal = (LayoutItemPortal) portalItem;
    assertTrue(portal != null);

    assertEquals("scene_cast", portal.getRelationshipNameUsed());
    assertEquals("Cast", portal.getTitle(defaultLocale));
    assertEquals("Szene Besetzung", portal.getTitle(germanLocale));

    // call getSuitableTableToViewDetails
    final TableToViewDetails viewDetails = filmManagerDocument.getPortalSuitableTableToViewDetails(portal);
    assertTrue(viewDetails != null);

    // Simulate a garbage collection
    System.gc();
    System.runFinalization();

    // Check if things are working like we expect
    assertEquals("characters", viewDetails.tableName);
    assertTrue(viewDetails.usesRelationship != null);
    final Relationship relationship = viewDetails.usesRelationship.getRelationship();
    assertTrue(relationship != null);
    assertEquals("cast", relationship.getName());
    assertTrue(viewDetails.usesRelationship.getRelatedRelationship() == null);

}

From source file:org.dspace.services.caching.CachingServiceImpl.java

public void resetCaches() {
    log.debug("resetCaches()");

    List<Cache> allCaches = getCaches();
    for (Cache cache : allCaches) {
        cache.clear();//from   www  .  ja  va 2  s .c  o m
    }

    if (getCacheProvider() != null) {
        try {
            getCacheProvider().resetCaches();
        } catch (Exception e) {
            log.warn("Failure in provider (" + getCacheProvider() + "): " + e.getMessage());
        }
    }

    System.runFinalization(); // force the JVM to try to clean up any remaining objects
    // DO NOT CALL System.gc() here or I will have you shot -AZ

    log.info("doReset(): Memory Recovery to: " + Runtime.getRuntime().freeMemory());
}

From source file:com.limegroup.gnutella.RouterService.java

/**
 * Starts a manual GC thread.//w ww.ja  v  a  2 s.  c o  m
 */
private void startManualGCThread() {
    Thread t = new ManagedThread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(5 * 60 * 1000);
                } catch (InterruptedException ignored) {
                }
                LOG.trace("Running GC");
                System.gc();
                LOG.trace("GC finished, running finalizers");
                System.runFinalization();
                LOG.trace("Finalizers finished.");
            }
        }
    }, "ManualGC");
    t.setDaemon(true);
    t.start();
    LOG.trace("Started manual GC thread.");
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
 * Delete the file now -- but in the event of failure, keep trying
 * in the future. /*  www . j  ava2 s  . c om*/
 * 
 * VERY IMPORTANT: Do not use with any file whose name/path may be 
 * reused, because the lagged delete could then wind up deleting the
 * newer file. Essentially, only to be used with uniquely-named temp
 * files. 
 * 
 * Necessary because some platforms (looking at you, 
 * JVM-on-Windows) will have deletes fail because of things like 
 * file-mapped buffers remaining, and there's no explicit way to 
 * unmap a buffer. (See 6-year-old Sun-stumping Java bug
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038 )
 * We just have to wait and retry. 
 * 
 * (Why not just File.deleteOnExit? There could be an arbitrary, 
 * unbounded number of files in such a situation, that are only 
 * deletable a few seconds or minutes after our first attempt.
 * Waiting for JVM exist could mean disk exhaustion. It's also
 * unclear if the native FS class implementations of deleteOnExit
 * use RAM per pending file.)
 * 
 * @param fileToDelete
 */
public static synchronized void deleteSoonerOrLater(File fileToDelete) {
    pendingDeletes.add(fileToDelete);
    // if things are getting out of hand, force gc/finalization
    if (pendingDeletes.size() > 50) {
        LOGGER.warning(">50 pending Files to delete; forcing gc/finalization");
        System.gc();
        System.runFinalization();
    }
    // try all pendingDeletes
    Iterator<File> iter = pendingDeletes.listIterator();
    while (iter.hasNext()) {
        File pending = iter.next();
        if (pending.delete()) {
            iter.remove();
        }
    }
    // if things are still out of hand, complain loudly
    if (pendingDeletes.size() > 50) {
        LOGGER.severe(">50 pending Files to delete even after gc/finalization");
    }
}