Example usage for java.lang System gc

List of usage examples for java.lang System gc

Introduction

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

Prototype

public static void gc() 

Source Link

Document

Runs the garbage collector in the Java Virtual Machine.

Usage

From source file:com.thoughtworks.go.agent.bootstrapper.DefaultAgentLauncherCreatorImpl.java

private void forceGCToReleaseAnyReferences() {
    System.gc();
}

From source file:com.univocity.app.DataUpdateTest.java

private void executeAndValidate(String entityName, boolean inserting, RowDataCollector dataCollector) {
    System.gc();
    loadProcess.execute(entityName);/*  w  ww .ja v a2 s.co  m*/

    Set<String> persistedRows = dataCollector.getPersistedData();
    Set<String> expectedRows = dataCollector.getExpected();

    if (!expectedRows.containsAll(persistedRows)) {
        @SuppressWarnings("unchecked")
        Collection<String> intersection = CollectionUtils.intersection(persistedRows, expectedRows);

        persistedRows.removeAll(intersection);
        expectedRows.removeAll(intersection);

        if (!isExpectedDiscrepancy(entityName, dataCollector.getFieldNames(), inserting, persistedRows)) {
            fail("Unexpected rows persisted:\n" + persistedRows.size()
                    + "\n\nRows expected but not persisted:\n" + expectedRows.size());
        }
    }
    System.gc();
}

From source file:org.mythdroid.services.JSONClient.java

/**
 * Perform a POST request to the specified path
 * @param path relative path of the query
 * @param query HashMap of query parameters
 * @return a JSONObject with the results
 * @throws IOException /* w  w  w.  j av  a2 s  . c o m*/
 */
public JSONObject Post(String path, Params query) throws IOException {
    try {
        return Request(new HttpPost(CreateURI(path, query)));
    } catch (URISyntaxException e) {
        ErrUtil.logErr(e);
        ErrUtil.report(e);
        throw new IOException(e.getMessage());
    } catch (IllegalStateException e) {
        ErrUtil.logErr(e);
        ErrUtil.report(e);
        throw new IOException(e.getMessage());
    } catch (OutOfMemoryError e) {
        System.gc();
        ErrUtil.logErr(e.getMessage());
        ErrUtil.report(e.getMessage());
        throw new IOException(e.getMessage());
    }
}

From source file:com.firegnom.valkyrie.map.tiled.TiledZoneLoader.java

@Override
public Zone load(String name) {
    long startTime, stopTime;
    try {//from  w  w  w  . jav a 2  s .co m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
        });
        startTime = System.currentTimeMillis();

        // map version
        JSONObject obj;
        int version = 0;
        try {
            obj = new JSONObject(convertStreamToString(rl.getResourceAsStreamDownload(name + ".json")));
            version = obj.getInt("version");
        } catch (JSONException e) {
            throw new ValkyrieRuntimeException(e);
        }

        InputStream inputStream = new GZIPInputStream(
                rl.getResourceAsStream(name + "-ver_" + version + ".tmx.gz", true));

        Document doc = builder.parse(inputStream);
        Element docElement = doc.getDocumentElement();
        stopTime = System.currentTimeMillis();
        Log.d(TAG, "Loaded Zone tmx file in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        System.gc();
        String orient = docElement.getAttribute("orientation");
        if (!orient.equals("orthogonal")) {
            throw new TiledLoaderException("Only orthogonal maps supported, found: " + orient);
        }

        int width = Integer.parseInt(docElement.getAttribute("width"));
        int height = Integer.parseInt(docElement.getAttribute("height"));
        int tileWidth = Integer.parseInt(docElement.getAttribute("tilewidth"));
        int tileHeight = Integer.parseInt(docElement.getAttribute("tileheight"));

        Zone zone = new Zone(name, width, height, tileWidth, tileHeight);
        // now read the map properties
        startTime = System.currentTimeMillis();
        getZoneProperties(zone, docElement);
        stopTime = System.currentTimeMillis();
        Log.d(TAG, "Loaded Zone Properties  in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        System.gc();
        startTime = System.currentTimeMillis();

        StringTileSet tileSet = null;
        NodeList setNodes = docElement.getElementsByTagName("tileset");
        int i;
        for (i = 0; i < setNodes.getLength(); i++) {
            Element current = (Element) setNodes.item(i);

            tileSet = getTileSet(zone, current, c);
            tileSet.index = i;
            Log.d(TAG, "Adding tileset to zone tilestets firstGID =" + tileSet.firstGID + ",lastGID="
                    + tileSet.lastGID + ", name=" + tileSet.imageName);
            zone.tileSets.add(tileSet.firstGID, tileSet.lastGID, tileSet);
        }
        stopTime = System.currentTimeMillis();
        Log.d("performance", "Loaded Zone tilesets in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        System.gc();
        startTime = System.currentTimeMillis();
        NodeList layerNodes = docElement.getElementsByTagName("layer");
        Element current;
        for (i = 0; i < layerNodes.getLength(); i++) {
            current = (Element) layerNodes.item(i);
            Layer layer = getLayer(zone, current);
            layer.index = i;
            zone.layers.add(layer);

        }

        stopTime = System.currentTimeMillis();
        Log.d(TAG, "Loaded Zone Layers in  in :" + ((stopTime - startTime) / 1000) + " secondsand "
                + ((stopTime - startTime) % 1000) + " miliseconds");
        NodeList objectGroupNodes = docElement.getElementsByTagName("objectgroup");
        for (i = 0; i < objectGroupNodes.getLength(); i++) {
            current = (Element) objectGroupNodes.item(i);
            if (current.getAttribute("name").equals("_ContextActions")) {
                zone.contextActions = getActionIndex(current);
            } else {
                appendMapObjects(current, zone.mapObjects);
            }
        }
        System.gc();
        return zone;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:MSUmpire.LCMSPeakStructure.LCMSPeakDIAMS2.java

public void ClearAllPeaks() {
    BaseClearAllPeaks();/*from w ww.  j av  a  2s. c om*/
    FragmentsClu2Cur = null;
    UnFragIonClu2Cur = null;
    //        FragmentMS1Ranking=null;
    //        FragmentUnfragRanking=null;
    MatchedFragmentMap = null;
    System.gc();
    //System.out.print("Peak data is released (Memory usage:" + Math.round((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576) + "MB)\n");
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

/**
 * Opens Bitmap from stream// w  w  w.  ja  v a 2 s.  c  o m
 *
 * @param stream - input stream
 * @param config decoding config
 * @return bitmap
 */
public static Bitmap proccessBitmap(InputStream stream, Bitmap.Config config) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inPreferredConfig = config;
    Bitmap bitmap = null;
    try {
        // decode image with appropriate options
        try {
            System.gc();
            bitmap = BitmapFactory.decodeStream(stream, null, opts);
        } catch (Exception ex) {
            Log.d("", "");
        } catch (OutOfMemoryError e) {
            Log.d("", "");
            System.gc();
            try {
                bitmap = BitmapFactory.decodeStream(stream, null, opts);
            } catch (Exception ex) {
                Log.d("", "");
            } catch (OutOfMemoryError ex) {
                Log.e("decodeImageFile", "OutOfMemoryError");
            }
        }
    } catch (Exception e) {
        Log.d("", "");
        return null;
    }

    return bitmap;
}

From source file:br.com.riselabs.cotonet.util.IOHandler.java

/**
 * Rewrite the repository folder for a given target system.
 * /*w  ww.  j  a v  a  2s . c o  m*/
 * @param sytemName
 * @return
 * @throws IOException
 */
public File makeSystemDirectory(String sytemName) throws IOException {
    File systemDir = new File(Directories.getReposDir(), sytemName);
    checkAndRemove(systemDir);
    systemDir.mkdirs();
    System.gc();
    return systemDir;
}

From source file:net.sf.jpam.AbstractPamTest.java

/**
 * Measures the memory use. Because Garbage Collection is done, memory should
 * not increase.//from  w  w w .j  a  va2 s  . c o  m
 *
 * @return the memory increase/- decrease in bytes
 * @throws InterruptedException
 */
protected long measureMemoryUse() throws InterruptedException {
    System.gc();
    Thread.sleep(3000);
    System.gc();
    long startingSize = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    return startingSize;
}

From source file:fr.inria.wimmics.coresetimer.CoreseTimer.java

public CoreseTimer run() throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        IOException, LoadException {
    LOGGER.entering(CoreseTimer.class.getName(), "run");
    assert (initialized);

    // Loading the nq data in corese, then applying several times the query.
    LOGGER.log(Level.INFO, "beginning with input #{0}", test.getInput());
    // require to have a brand new adapter for each new input set.
    adapter = (CoreseAdapter) Class.forName(adapterName).newInstance();

    String inputFileName = "";
    switch (mode) {
    case MEMORY: {
        inputFileName += test.getInput();
        adapter.preProcessing(inputFileName, true);
        break;/*from w  w w  . j av a  2 s.  c  om*/
    }
    case DB: {
        inputFileName += test.getInputDb();
        System.setProperty("fr.inria.corese.tinkerpop.dbinput", inputFileName);
        adapter.preProcessing(inputFileName, false);
        break;
    }
    }

    String query = test.getRequest();
    LOGGER.log(Level.INFO, "processing nbQuery #{0}", query);
    stats = new DescriptiveStatistics();
    statsMemory = new DescriptiveStatistics();
    int nbCycles = test.getMeasuredCycles() + test.getWarmupCycles();
    boolean measured = true;
    for (int i = 0; i < nbCycles; i++) {
        LOGGER.log(Level.INFO, "iteration #{0}", i);
        System.gc();
        final long startTime = System.currentTimeMillis();
        LOGGER.log(Level.INFO, "before query");

        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(new Runnable() {
            @Override
            public void run() {
                adapter.execQuery(query);
            }
        });

        try {
            future.get(1, TimeUnit.HOURS);
            measured = true;
        } catch (InterruptedException | TimeoutException e) {
            future.cancel(true);
            measured = false;
            LOGGER.log(Level.WARNING, "Terminated!");
        } catch (ExecutionException ex) {
            Logger.getLogger(CoreseTimer.class.getName()).log(Level.SEVERE, null, ex);
        }
        executor.shutdownNow();

        LOGGER.log(Level.INFO, "after query");
        final long endTime = System.currentTimeMillis();
        long delta = endTime - startTime;
        long memoryUsage = getMemoryUsage();
        LOGGER.info(String.format("elapsed time = %d ms", delta));
        LOGGER.info(String.format("used memory = %d bytes", memoryUsage));
        if (i >= test.getWarmupCycles()) {
            if (!measured) {
                while (i < nbCycles) {
                    stats.addValue(-100);
                    statsMemory.addValue(memoryUsage);
                    i++;
                }
            } else {
                stats.addValue(delta);
                statsMemory.addValue(memoryUsage);
            }
        }
    }
    adapter.saveResults(test.getOutputPath());
    mappings = adapter.getMappings();
    adapter.postProcessing();
    LOGGER.exiting(CoreseTimer.class.getName(), "run");
    return this;
}

From source file:com.linkedin.cubert.utils.SerializedTupleStore.java

public void clear() {
    pbaos.reset();/*w w  w .j a v a  2 s  .  c o  m*/

    if (startOffsetList != null)
        startOffsetList.clear();

    long before = Runtime.getRuntime().freeMemory();
    System.gc();
    long after = Runtime.getRuntime().freeMemory();
    print.f("Memory. Before=%d After=%d. Diff=%d", before, after, after - before);
}