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:Main.java

public static void main(String[] args) {

    Runtime runTime = Runtime.getRuntime();
    runTime.gc();
    System.out.println("Completed.");
}

From source file:MemoryDemo.java

public static void main(String args[]) {
    Runtime r = Runtime.getRuntime();
    long mem1, mem2;
    Integer someints[] = new Integer[1000];

    System.out.println("Total memory is: " + r.totalMemory());

    mem1 = r.freeMemory();/*from  ww w  . j ava2  s  . co m*/
    System.out.println("Initial free memory: " + mem1);
    r.gc();
    mem1 = r.freeMemory();
    System.out.println("Free memory after garbage collection: " + mem1);

    for (int i = 0; i < 1000; i++)
        someints[i] = new Integer(i); // allocate integers

    mem2 = r.freeMemory();
    System.out.println("Free memory after allocation: " + mem2);
    System.out.println("Memory used by allocation: " + (mem1 - mem2));

    for (int i = 0; i < 1000; i++)
        someints[i] = null;

    r.gc(); // request garbage collection

    mem2 = r.freeMemory();
    System.out.println("Free memory after collecting" + " discarded Integers: " + mem2);

}

From source file:MainClass.java

public static void main(String args[]) {
    Runtime r = Runtime.getRuntime();
    long mem1, mem2;
    Integer someints[] = new Integer[10000];

    System.out.println("Total memory is: " + r.totalMemory());

    mem1 = r.freeMemory();/*ww w  .j av  a  2  s. c  om*/
    System.out.println("Initial free memory: " + mem1);
    r.gc();
    mem1 = r.freeMemory();
    System.out.println("Free memory after garbage collection: " + mem1);

    for (int i = 0; i < someints.length; i++)
        someints[i] = new Integer(i); // allocate integers

    mem2 = r.freeMemory();
    System.out.println("Free memory after allocation: " + mem2);
    System.out.println("Memory used by allocation: " + (mem1 - mem2));

    for (int i = 0; i < someints.length; i++)
        someints[i] = null;

    r.gc(); // request garbage collection

    mem2 = r.freeMemory();
    System.out.println("Free memory after collecting" + " discarded Integers: " + mem2);

}

From source file:org.apache.ranger.policyengine.RangerPluginPerfTester.java

public static void main(String[] args) {

    if (!parseArguments(args)) {
        System.err.println("Exiting.. ");
        System.exit(-1);/*from  w w w . j a  v  a  2 s.  co m*/
    }

    System.out.println("Arguments:");
    System.out.println("\t\tservice-type:\t\t\t" + serviceType);
    System.out.println("\t\tservice-name:\t\t\t" + serviceName);
    System.out.println("\t\tapp-id:\t\t\t\t" + appId);
    System.out.println("\t\tranger-host:\t\t\t" + rangerHostName);
    System.out.println("\t\tsocket-read-timeout:\t\t" + socketReadTimeout);
    System.out.println("\t\tpolling-interval:\t\t" + pollingInterval);
    System.out.println("\t\tpolicy-cache-dir:\t\t" + policyCacheDir);
    System.out.println("\t\tuse-cached-policy-evaluator:\t" + useCachedPolicyEvaluator);
    System.out.println("\n\n");

    Path filePath = buildConfigurationFile();

    if (filePath != null) {
        RangerConfiguration rangerConfig = RangerConfiguration.getInstance();
        rangerConfig.addResource(filePath);

        plugin = new RangerBasePlugin(serviceType, appId);

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

        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();

        System.out.println("Initial Memory Statistics:");
        System.out.println("\t\tMaximum Memory available for the process:\t" + runtime.maxMemory());
        System.out.println("\t\tInitial In-Use memory:\t\t\t\t" + (totalMemory - freeMemory));
        System.out.println("\t\tInitial Free memory:\t\t\t\t" + freeMemory);

        System.out.println("\n\n");

        plugin.init();

        while (true) {

            runtime.gc();

            freeMemory = runtime.freeMemory();
            totalMemory = runtime.totalMemory();

            System.out.println("Memory Statistics:");
            System.out.println("\t\tCurrently In-Use memory:\t" + (totalMemory - freeMemory));
            System.out.println("\t\tCurrently Free memory:\t\t" + freeMemory);

            System.out.println("\n\n");

            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e) {

                System.err.println("Main thread interrupted..., exiting...");
                break;
            }
        }
    } else {
        System.err.println("Failed to build configuration file");
    }
}

From source file:org.apache.ranger.policyengine.RangerPolicyenginePerfTester.java

public static void main(String[] args) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerPolicyenginePerfTester.main()");
    }/*from w  w  w. j a  v  a  2  s  .c o  m*/

    CommandLineParser commandLineParser = new CommandLineParser();

    PerfTestOptions perfTestOptions = commandLineParser.parse(args);

    if (perfTestOptions != null) {
        URL statCollectionFileURL = perfTestOptions.getStatCollectionFileURL();

        List<String> perfModuleNames = statCollectionFileURL != null
                ? buildPerfModuleNames(statCollectionFileURL)
                : new ArrayList<String>();

        PerfDataRecorder.initialize(perfModuleNames);

        URL servicePoliciesFileURL = perfTestOptions.getServicePoliciesFileURL();

        RangerPolicyEngineOptions policyEngineOptions = new RangerPolicyEngineOptions();
        policyEngineOptions.disableTagPolicyEvaluation = false;
        policyEngineOptions.evaluatorType = RangerPolicyEvaluator.EVALUATOR_TYPE_OPTIMIZED;
        policyEngineOptions.disableTrieLookupPrefilter = perfTestOptions.getIsTrieLookupPrefixDisabled();

        PerfTestEngine perfTestEngine = new PerfTestEngine(servicePoliciesFileURL, policyEngineOptions,
                perfTestOptions.getIsDynamicReorderingDisabled());
        if (!perfTestEngine.init()) {
            LOG.error("Error initializing test data. Existing...");
            System.exit(1);
        }

        URL[] requestFileURLs = perfTestOptions.getRequestFileURLs();
        int requestFilesCount = requestFileURLs.length;

        // warm-up policy engine
        LOG.error("Warming up..");
        try {
            for (URL requestFileURL : requestFileURLs) {
                PerfTestClient perfTestClient = new PerfTestClient(perfTestEngine, 0, requestFileURL, 1);

                if (perfTestClient.init()) {
                    perfTestClient.start();
                    perfTestClient.join();
                } else {
                    LOG.error("Error initializing warm-up PerfTestClient");
                }
            }
        } catch (Throwable t) {
            LOG.error("Error during warmup", t);
        }
        LOG.error("Warmed up!");

        PerfDataRecorder.clearStatistics();

        int clientsCount = perfTestOptions.getConcurrentClientCount();
        List<PerfTestClient> perfTestClients = new ArrayList<PerfTestClient>(clientsCount);

        for (int i = 0; i < clientsCount; i++) {

            URL requestFileURL = requestFileURLs[i % requestFilesCount];

            PerfTestClient perfTestClient = new PerfTestClient(perfTestEngine, i, requestFileURL,
                    perfTestOptions.getIterationsCount());

            if (!perfTestClient.init()) {
                LOG.error("Error initializing PerfTestClient: (id=" + i + ")");
            } else {
                perfTestClients.add(perfTestClient);
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Number of perfTestClients=" + perfTestClients.size());
        }

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

        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();

        LOG.info("Memory stats: max-available=:" + runtime.maxMemory() + "; in-use="
                + (totalMemory - freeMemory) + "; free=" + freeMemory);

        LOG.info("Starting " + perfTestClients.size() + " clients..");
        for (PerfTestClient client : perfTestClients) {
            try {
                client.start();
            } catch (Throwable t) {
                LOG.error("Error in starting client: " + client.getName(), t);
            }
        }
        LOG.info("Started " + perfTestClients.size() + " clients");

        LOG.info("Waiting for " + perfTestClients.size() + " clients to finish up");

        for (PerfTestClient client : perfTestClients) {
            while (client.isAlive()) {
                try {
                    client.join(1000);

                    runtime.gc();

                    totalMemory = runtime.totalMemory();
                    freeMemory = runtime.freeMemory();

                    LOG.info("Memory stats: max-available=:" + runtime.maxMemory() + "; in-use="
                            + (totalMemory - freeMemory) + "; free=" + freeMemory);

                } catch (InterruptedException interruptedException) {
                    LOG.error("PerfTestClient.join() was interrupted");
                }
            }
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("<== RangerPolicyenginePerfTester.main()");
        }

        LOG.info("Completed performance-run");

        perfTestEngine.cleanup();

        PerfDataRecorder.printStatistics();
    }

    LOG.info("Exiting...");

}

From source file:io.anserini.index.UserPostFrequencyDistribution.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));

    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(OptionBuilder.withArgName("collection").hasArg()
            .withDescription("source collection directory").create(COLLECTION_OPTION));
    options.addOption(OptionBuilder.withArgName("property").hasArg()
            .withDescription("source collection directory").create("property"));
    options.addOption(OptionBuilder.withArgName("collection_pattern").hasArg()
            .withDescription("source collection directory").create("collection_pattern"));

    CommandLine cmdline = null;//  w w w.  ja  v a2  s . c o  m
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(UserPostFrequencyDistribution.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    textOptions.setStoreTermVectors(true);

    LOG.info("collection: " + collectionPath);
    LOG.info("collection_pattern " + cmdline.getOptionValue("collection_pattern"));
    LOG.info("property " + cmdline.getOptionValue("property"));
    LongOpenHashSet deletes = null;

    long startTime = System.currentTimeMillis();
    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    final JsonStatusCorpusReader stream = new JsonStatusCorpusReader(file,
            cmdline.getOptionValue("collection_pattern"));

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {

            try {

                stream.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            ;

            System.out.println("# of users indexed this round: " + userIndexedCount);

            System.out.println("Shutting down");

        }
    });
    Status status;
    boolean readerNotInitialized = true;

    try {
        Properties prop = new Properties();
        while ((status = stream.next()) != null) {

            // try{
            // status = DataObjectFactory.createStatus(s);
            // if (status==null||status.getText() == null) {
            // continue;
            // }}catch(Exception e){
            //
            // }
            //

            boolean pittsburghRelated = false;
            try {

                if (Math.abs(status.getLongitude() - pittsburghLongitude) < 0.05d
                        && Math.abs(status.getlatitude() - pittsburghLatitude) < 0.05d)
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getPlace().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getUserLocation().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            try {
                if (status.getText().contains("Pittsburgh"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            if (pittsburghRelated) {

                int previousPostCount = 0;

                if (prop.containsKey(String.valueOf(status.getUserid()))) {
                    previousPostCount = Integer
                            .valueOf(prop.getProperty(String.valueOf(status.getUserid())).split(" ")[1]);
                }

                prop.setProperty(String.valueOf(status.getUserid()),
                        String.valueOf(status.getStatusesCount()) + " " + (1 + previousPostCount));
                if (prop.size() > 0 && prop.size() % 1000 == 0) {
                    Runtime runtime = Runtime.getRuntime();
                    runtime.gc();
                    System.out.println("Property size " + prop.size() + "Memory used:  "
                            + ((runtime.totalMemory() - runtime.freeMemory()) / (1024L * 1024L)) + " MB\n");
                }
                OutputStream output = new FileOutputStream(cmdline.getOptionValue("property"), false);
                prop.store(output, null);
                output.close();

            }
        }
        //         prop.store(output, null);
        LOG.info(String.format("Total of %s statuses added", userIndexedCount));
        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        stream.close();
    }
}

From source file:gov.jgi.meta.hadoop.input.FastaBlockLineReader.java

public static void main(String[] args) {

    int num = 1;/*from  w  ww . j  a v  a  2s  . com*/
    int last = -1;

    do {
        try {
            FileInputStream fstream = new FileInputStream("/scratch/karan/30mb.fas");
            FastaBlockLineReader fblr = new FastaBlockLineReader(fstream);

            Text key = new Text();
            Map<String, String> setofreads = new HashMap<String, String>();
            Map<String, String> setofreadsTotal = new HashMap<String, String>();
            int length = (int) (Math.random() * 10000);
            length = 3000000;
            System.out.println("lenght = " + length);

            int total = 0;

            fblr.readLine(key, setofreads, Integer.MAX_VALUE, length);
            //            System.out.println("setofreads.size = " + setofreads.size());
            total += setofreads.size();
            //for (String s : setofreads.keySet()) {
            //                System.out.println(s);
            //            }
            Runtime r = Runtime.getRuntime();
            while (setofreads.size() > 0) {
                setofreadsTotal.putAll(setofreads);
                setofreads.clear();
                fblr.readLine(key, setofreads, Integer.MAX_VALUE, length);
                //              System.out.println("setofreads.size = " + setofreads.size());
                total += setofreads.size();

                r.gc();
            }
            System.out.println("total = " + total);
            System.out.println("heap size = " + r.totalMemory() / 1048576);

            if (last != -1) {
                if (last != total) {
                    System.out.println(
                            "error!!!, length = " + length + ": last = " + last + " current = " + total);
                }
            }
            last = total;

        } catch (Exception e) {
            System.out.println(e);
        }
    } while (num-- > 0);

}

From source file:org.cloudata.core.tabletserver.ColumnCollection.java

License:asdf

public static void main(String[] args) throws Exception {
    /*/* www .  j  a  v  a  2  s  . c  om*/
    Assuming 32-bit words and a 12 byte overhead per array instance,
    int[4,100,000][2][2][5]
    4th dim. = overhead + length * sizeof(int) = 12 + 5 * 4 = 32
    3rd dim. = overhead + length * (sizeof(ref) + sizeof(4th_dim)) = 12 + 2 * (4 + 32) = 84
    2nd dim. = overhead + length * (sizeof(ref) + sizeof(3rd_dim)) = 12 + 2 * (4 + 84) = 188
    1st dim. = overhead + length * (sizeof(ref) + sizeof(2nd_dim)) = 12 + 4,100,000 * (4 + 188) = 787,200,012
            
    byte[]? ? = 12 + ((length + 3)/8) * 8 + 4
            
    byte?  0 ~ 4 12 + 4 ?
      ???  8 ?
     : 0 ~ 4: 16, 5 ~ 12: 24, 13 ~ 20: 32 
             
     ? Text?  ? header 4byte, byte[] ? 4byte, int length 4byte, length? ? 4 byte = 16 + len(byte[])
    */

    //Cell.Key, Row.Key: 16byte + byte[]
    //ColumnValue: 16 + rowKey, columnKey, value
    //ColumnCollection: ColumnValue + 124

    Runtime runtime = Runtime.getRuntime();
    Cell.Key columnKey = new Cell.Key("123");
    Row.Key rowKey = new Row.Key("123");
    ColumnValue columnValue = new ColumnValue();

    ColumnCollection collection = new ColumnCollection(new CloudataConf());
    collection.addValue(rowKey, new ColumnValue(rowKey, columnKey, "".getBytes()), 0);

    byte[] valueBuf = "0123456789".getBytes();
    byte[] columnKeyBuf = "abcdefghij".getBytes();
    byte[] rowKeyBuf = "!@#$%^&*()".getBytes();

    Cell.Key columnKey2 = new Cell.Key("qwertyuiop".getBytes());
    Row.Key rowKey2 = new Row.Key("asdfghjkl;".getBytes());
    ColumnValue columnValue2 = new ColumnValue(rowKey2, columnKey2, "zxcvbnm,./".getBytes());

    columnKey = new Cell.Key(columnKeyBuf);
    rowKey = new Row.Key(rowKeyBuf);
    columnValue = new ColumnValue(rowKey, columnKey, valueBuf);

    runtime.gc();
    long before = runtime.freeMemory();

    collection.addValue(rowKey, columnValue, 0);
    collection.addValue(rowKey2, columnValue2, 0);

    runtime.gc();
    long after = runtime.freeMemory();

    int byteLen = 12 + ((valueBuf.length + 3) / 8) * 8 + 4;
    int rowKeyLen = 16 + byteLen;
    int columnKeyLen = 16 + byteLen;

    int columnValueLen = 16 + rowKeyLen + columnKeyLen + byteLen;

    System.out.printf("%d - %d = %d, %d\n", before, after, (before - after), columnValueLen);
}

From source file:CGgui.java

public static void main(String[] args) {
    //initialize gui

    try {//from  w  w  w  . j a  v  a 2s  . c  om
        CGgui CGinterface = new CGgui();
        CGinterface.show();

        /*Code for Debugging purposes*/

        //garbage collect
        Runtime r = Runtime.getRuntime();
        r.gc();
    } catch (IndexOutOfBoundsException e) {
        System.err.println("Caught out of bounds exception");
        System.exit(-1);
    }

    //grab file
    //   CGinterface.CGdata = CGinterface.LoadSeq("chr21_random.fa");

    //process data
    //find distances of 30
    //   double[] length = CGinterface.getLengths(30);

    //graph data
    //   CGinterface.addData(CGinterface.header,length,100000,CGinterface.MIN,CGinterface.MAX);
    //   CGinterface.MovingAverage(150);
    //   CGinterface.Bezier(.01);
}

From source file:Mem.java

public static void gc() {
    Runtime r = Runtime.getRuntime();
    r.runFinalization();
    r.gc();
}