Example usage for java.lang Runtime gc

List of usage examples for java.lang Runtime gc

Introduction

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

Prototype

public native void gc();

Source Link

Document

Runs the garbage collector in the Java Virtual Machine.

Usage

From source file:edu.umn.cs.spatialHadoop.visualization.MultilevelPlot.java

public static Job plot(Path[] inPaths, Path outPath, Class<? extends Plotter> plotterClass,
        OperationsParams params) throws IOException, InterruptedException, ClassNotFoundException {
    if (params.getBoolean("showmem", false)) {
        // Run a thread that keeps track of used memory
        Thread memThread = new Thread(new Thread() {
            @Override/*from   www. ja va  2s.c  om*/
            public void run() {
                Runtime runtime = Runtime.getRuntime();
                while (true) {
                    try {
                        Thread.sleep(60000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runtime.gc();
                    LOG.info("Memory usage: "
                            + ((runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024 * 1024)) + "GB.");
                }
            }
        });
        memThread.setDaemon(true);
        memThread.start();
    }

    // Decide how to run it based on range of levels to generate
    String[] strLevels = params.get("levels", "7").split("\\.\\.");
    int minLevel, maxLevel;
    if (strLevels.length == 1) {
        minLevel = 0;
        maxLevel = Integer.parseInt(strLevels[0]) - 1;
    } else {
        minLevel = Integer.parseInt(strLevels[0]);
        maxLevel = Integer.parseInt(strLevels[1]);
    }
    // Create an output directory that will hold the output of the two jobs
    FileSystem outFS = outPath.getFileSystem(params);
    outFS.mkdirs(outPath);

    Job runningJob = null;
    if (OperationsParams.isLocal(params, inPaths)) {
        // Plot local
        plotLocal(inPaths, outPath, plotterClass, params);
    } else {
        int maxLevelWithFlatPartitioning = params.getInt(FlatPartitioningLevelThreshold, 4);
        if (minLevel <= maxLevelWithFlatPartitioning) {
            OperationsParams flatPartitioning = new OperationsParams(params);
            flatPartitioning.set("levels", minLevel + ".." + Math.min(maxLevelWithFlatPartitioning, maxLevel));
            flatPartitioning.set("partition", "flat");
            LOG.info("Using flat partitioning in levels " + flatPartitioning.get("levels"));
            runningJob = plotMapReduce(inPaths, new Path(outPath, "flat"), plotterClass, flatPartitioning);
        }
        if (maxLevel > maxLevelWithFlatPartitioning) {
            OperationsParams pyramidPartitioning = new OperationsParams(params);
            pyramidPartitioning.set("levels",
                    Math.max(minLevel, maxLevelWithFlatPartitioning + 1) + ".." + maxLevel);
            pyramidPartitioning.set("partition", "pyramid");
            LOG.info("Using pyramid partitioning in levels " + pyramidPartitioning.get("levels"));
            runningJob = plotMapReduce(inPaths, new Path(outPath, "pyramid"), plotterClass,
                    pyramidPartitioning);
        }
        // Write a new HTML file that displays both parts of the pyramid
        // Add an HTML file that visualizes the result using Google Maps
        LineReader templateFileReader = new LineReader(
                MultilevelPlot.class.getResourceAsStream("/zoom_view.html"));
        PrintStream htmlOut = new PrintStream(outFS.create(new Path(outPath, "index.html")));
        Text line = new Text();
        while (templateFileReader.readLine(line) > 0) {
            String lineStr = line.toString();
            lineStr = lineStr.replace("#{TILE_WIDTH}", Integer.toString(params.getInt("tilewidth", 256)));
            lineStr = lineStr.replace("#{TILE_HEIGHT}", Integer.toString(params.getInt("tileheight", 256)));
            lineStr = lineStr.replace("#{MAX_ZOOM}", Integer.toString(maxLevel));
            lineStr = lineStr.replace("#{MIN_ZOOM}", Integer.toString(minLevel));
            lineStr = lineStr.replace("#{TILE_URL}", "(zoom <= " + maxLevelWithFlatPartitioning
                    + "? 'flat' : 'pyramid')+('/tile-' + zoom + '-' + coord.x + '-' + coord.y + '.png')");

            htmlOut.println(lineStr);
        }
        templateFileReader.close();
        htmlOut.close();
    }

    return runningJob;
}

From source file:ffx.HeadlessMain.java

/**
 * Complete initializations./*from  w  w  w. jav a  2 s.  c o m*/
 *
 * @param commandLineFile a {@link java.io.File} object.
 * @param argList a {@link java.util.List} object.
 * @param logHandler a {@link ffx.ui.LogHandler} object.
 */
public HeadlessMain(File commandLineFile, List<String> argList, LogHandler logHandler) {
    // Start a timer.
    stopWatch.start();

    // Construct the MainPanel, set it's LogHandler, and initialize then it.
    mainPanel = new MainPanel();
    logHandler.setMainPanel(mainPanel);
    mainPanel.initialize();

    // Open the supplied script file.
    if (commandLineFile != null) {
        if (!commandLineFile.exists()) {
            /**
             * See if the commandLineFile is an embedded script.
             */
            String name = commandLineFile.getName();
            name = name.replace('.', '/');
            String pathName = "ffx/scripts/" + name;
            ClassLoader loader = getClass().getClassLoader();
            URL embeddedScript = loader.getResource(pathName + ".ffx");
            if (embeddedScript == null) {
                embeddedScript = loader.getResource(pathName + ".groovy");
            }
            if (embeddedScript != null) {
                try {
                    commandLineFile = new File(FFXClassLoader.copyInputStreamToTmpFile(
                            embeddedScript.openStream(), commandLineFile.getName(), ".ffx"));
                } catch (Exception e) {
                    logger.warning("Exception extracting embedded script " + embeddedScript.toString() + "\n"
                            + e.toString());
                }
            }
        }
        if (commandLineFile.exists()) {
            mainPanel.getModelingShell().setArgList(argList);
            mainPanel.open(commandLineFile, null);
        } else {
            logger.warning(format("%s was not found.", commandLineFile.toString()));
        }
    }

    /**
     * Print start-up information.
     */
    if (logger.isLoggable(Level.FINE)) {
        StringBuilder sb = new StringBuilder();
        sb.append(format("\n Start-up Time (msec): %s.", stopWatch.getTime()));
        Runtime runtime = Runtime.getRuntime();
        runtime.runFinalization();
        runtime.gc();
        long occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
        long KB = 1024;
        sb.append(format("\n In-Use Memory   (Kb): %d", occupiedMemory / KB));
        sb.append(format("\n Free Memory     (Kb): %d", runtime.freeMemory() / KB));
        sb.append(format("\n Total Memory    (Kb): %d", runtime.totalMemory() / KB));
        logger.fine(sb.toString());
    }
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void testToJsonLibOnInheritedClassInput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    SpecialPerson[] sparesult = new SpecialPerson[TEST_SIZE];
    Runtime r = Runtime.getRuntime();
    r.gc();
    long personStart = r.totalMemory() - r.freeMemory();
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }/* w  w  w  . j a  v  a 2 s . c  o  m*/
    long personEnd = r.totalMemory() - r.freeMemory();

    String[] serializeOutput = new String[TEST_SIZE];
    r.gc();
    for (int i = 0; i < TEST_SIZE; i++) {

        serializeOutput[i] = beanJsonLibConverter.convertToString(spa[i]);
    }

    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startInput = System.currentTimeMillis();
    for (int i = 0; i < TEST_SIZE; i++) {
        sparesult[i] = beanJsonLibConverter.convertToObject(serializeOutput[i], SpecialPerson.class);
    }
    long endInput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();

    log.info("SF JSON Lib Input " + average(startInput, endInput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(personStart, personEnd, TEST_SIZE))
            + " heap bytes/conversion, person object consumed on average "
            + average(personStart, personEnd, TEST_SIZE));
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void XtestToJsonOnInheritedClassInput() throws Exception {
    SpecialPerson[] spa = new SpecialPerson[TEST_SIZE];
    SpecialPerson[] sparesult = new SpecialPerson[TEST_SIZE];
    Runtime r = Runtime.getRuntime();
    r.gc();
    long personStart = r.totalMemory() - r.freeMemory();
    for (int i = 0; i < TEST_SIZE; i++) {
        spa[i] = new SpecialPerson(String.valueOf(i), "robot", "nonsense");
    }//from  w w w  .  jav  a  2  s  .c  om
    long personEnd = r.totalMemory() - r.freeMemory();

    String[] serializeOutput = new String[TEST_SIZE];
    r.gc();
    for (int i = 0; i < TEST_SIZE; i++) {

        serializeOutput[i] = beanJsonConverter.convertToString(spa[i]);
    }

    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startInput = System.currentTimeMillis();

    for (int i = 0; i < TEST_SIZE; i++) {
        sparesult[i] = beanJsonConverter.convertToObject(serializeOutput[i], SpecialPerson.class);
    }
    long endInput = System.currentTimeMillis();
    long memend = r.totalMemory() - r.freeMemory();

    log.info("SF JSON Lib Input " + average(startInput, endInput, TEST_SIZE) + " ms/conversion, "
            + (average(memstart, memend, TEST_SIZE) - average(personStart, personEnd, TEST_SIZE))
            + " heap bytes/conversion, person object consumed on average "
            + average(personStart, personEnd, TEST_SIZE));
}

From source file:org.apache.shindig.social.opensocial.util.JsonConverterPerformancePerf.java

public void testToJsonLibOnInheritedClassOutput() 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 w w.  j ava 2 s .c  om*/
    Runtime r = Runtime.getRuntime();
    r.gc();
    long memstart = r.totalMemory() - r.freeMemory();
    long startOutput = System.currentTimeMillis();
    String[] output = new String[TEST_SIZE];
    for (int i = 0; i < TEST_SIZE; i++) {
        output[i] = beanJsonLibConverter.convertToString(spa[i]);
    }
    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();

    /*
     * Output the time per conversion and the memory usage - the output per
     * conversion.
     *
     */

    log.info("SF 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.openddal.test.BaseTestCase.java

/**
 * Get the number of bytes heap memory in use.
 *
 * @return the used bytes//  ww w.  ja  v  a  2 s.  c om
 */
public static long getMemoryUsedBytes() {
    Runtime rt = Runtime.getRuntime();
    long memory = Long.MAX_VALUE;
    for (int i = 0; i < 8; i++) {
        rt.gc();
        long memNow = rt.totalMemory() - rt.freeMemory();
        if (memNow >= memory) {
            break;
        }
        memory = memNow;
    }
    return memory;
}

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");
    }/*from w  w  w.  java  2s. c  o  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:ffx.ui.UIDataConverter.java

/**
 * Rather verbose output for timed File Operations makes it easy to grep log
 * files for specific information.//from  w w  w .jav a  2 s  .  c  o m
 */
private void startTimer() {
    Runtime runtime = Runtime.getRuntime();
    if (gc) {
        runtime.runFinalization();
        runtime.gc();
    }
    occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
    time -= System.nanoTime();
}

From source file:ffx.ui.UIDataConverter.java

private void stopTimer(FFXSystem ffxSystem) {
    time += System.nanoTime();//from  w  w w  .ja  va 2  s.c o  m
    logger.log(Level.INFO, " Opened {0} with {1} atoms.\n File Op Time  (msec): {2}",
            new Object[] { ffxSystem.toString(), ffxSystem.getAtomList().size(), time * 1.0e-9 });
    Runtime runtime = Runtime.getRuntime();
    if (gc) {
        runtime.runFinalization();
        runtime.gc();
        long moleculeMemory = (runtime.totalMemory() - runtime.freeMemory()) - occupiedMemory;
        logger.log(Level.INFO, " System Memory  (Kb): {0}", moleculeMemory / KB);
    }
    occupiedMemory = runtime.totalMemory() - runtime.freeMemory();
    if (gc) {
        logger.log(Level.INFO, " Memory In Use  (Kb): {0}", occupiedMemory / KB);
    }
}

From source file:com.flat20.fingerplay.FingerPlayActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {

    // Init needs to be done first!
    mSettingsModel = SettingsModel.getInstance();
    mSettingsModel.init(this);

    mMidiControllerManager = MidiControllerManager.getInstance();

    super.onCreate(savedInstanceState);

    Runtime r = Runtime.getRuntime();
    r.gc();

    Toast info = Toast.makeText(this, "Go to http://goddchen.github.io/Fingerplay-Midi/ for help.",
            Toast.LENGTH_LONG);/*  w  ww  .  j  a  v a2 s  . co m*/
    info.show();

    // Sensor code
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    sensors = new ArrayList<Sensor>(sensorManager.getSensorList(Sensor.TYPE_ALL));
    startSensors();

    // Simple splash animation

    Splash navSplash = new Splash(mNavigationOverlay, 64, 30, mWidth, mNavigationOverlay.x);
    mNavigationOverlay.x = mWidth;
    AnimationManager.getInstance().add(navSplash);

    Splash mwcSplash = new Splash(mMidiWidgetsContainer, 64, 40, -mWidth, mMidiWidgetsContainer.x);
    mMidiWidgetsContainer.x = -mWidth;
    AnimationManager.getInstance().add(mwcSplash);

    if (BuildConfig.DEBUG) {
        if (TextUtils.isEmpty(PreferenceManager.getDefaultSharedPreferences(this)
                .getString("settings_server_address", null))) {
            Toast.makeText(this, R.string.toast_server_not_setup, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(getApplicationContext(), SettingsView.class));
        }
    } else {
        boolean result = bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
                mBillingServiceConnection, Context.BIND_AUTO_CREATE);
        if (!result) {
            unableToVerifyLicense(getString(R.string.billing_error_init), false);
        }
    }
}