Example usage for java.lang Runtime freeMemory

List of usage examples for java.lang Runtime freeMemory

Introduction

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

Prototype

public native long freeMemory();

Source Link

Document

Returns the amount of free memory in the Java Virtual Machine.

Usage

From source file:Main.java

public static void main(String[] args) {

    Runtime runTime = Runtime.getRuntime();

    // print the number of free bytes
    System.out.println(runTime.freeMemory());

}

From source file:Main.java

public static void main(String[] args) {

    // get the current runtime assosiated with this process
    Runtime run = Runtime.getRuntime();

    // print the current free memory for this runtime
    System.out.println("" + run.freeMemory());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Runtime runTime = Runtime.getRuntime();

    long heapSize = runTime.totalMemory();

    long heapMaxSize = runTime.maxMemory();

    long heapFreeSize = runTime.freeMemory();

}

From source file:substring.Static.java

public static void main(String[] args) throws Throwable {

    Runtime rt = Runtime.getRuntime();
    double alloc = rt.totalMemory() / 1000.0;
    double free = rt.freeMemory() / 1000.0;

    System.out.printf("Allocated (before substring operation) : %.2f kb\nFree: %.2f kb\n\n", alloc, free);
    Scanner in = new Scanner(new File("my_file.txt"));
    List<String> al = new ArrayList<String>();

    while (in.hasNextLine()) {
        String s = in.nextLine();
        /* Problem Code */
        //al.add(s.substring(0, 200)); // extracts first 200 characters
        /* Solution Code */
        //al.add(new String(s.substring(0,200))); 
        /* Using static menthod */
        // al.add(substring(s, 0, 200));
        /* Using apache */
        al.add(StringUtils.substring(s, 0, 200));
    }//from ww  w  .jav  a2s  . co m

    alloc = rt.totalMemory() / 1000.0;
    free = rt.freeMemory() / 1000.0;
    System.out.printf("\nAllocated (after substring operation): %.2f kb\nFree: %.2f kb\n\n", alloc, free);

    in.close();
    System.gc();

    alloc = rt.totalMemory() / 1000.0;
    free = rt.freeMemory() / 1000.0;
    System.out.printf("\nAllocated (after System.gc() operation):: %.2f kb\nFree: %.2f kb\n\n", alloc, free);
}

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();
    System.out.println("Initial free memory: " + mem1);
    r.gc();/*from  w ww. java2s  .  c  o m*/
    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();
    System.out.println("Initial free memory: " + mem1);
    r.gc();/*from   ww  w.ja v  a2  s  . c o  m*/
    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 ww  .ja v a 2s. 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   ww  w  . ja v  a 2  s  .  c  om

    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;/*from  w  ww.  j  a va 2s .  c om*/
    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:com.yobidrive.diskmap.buckets.BucketTableManager.java

public static void main(String[] args) {

    try {/*from w  w  w .j  a  va 2  s.co  m*/
        BucketTableManager nw = new BucketTableManager("/Users/Francois/Documents/NEEDLES/0.TestStore", 100,
                1000000, 3000L, true);

        nw.initialize();
        System.out.println(
                "Bucket table initialization: " + (nw.getCheckPoint().isEmpty() ? " Repair required" : " OK"));

        Runtime runtime = Runtime.getRuntime();
        long before = runtime.totalMemory() - runtime.freeMemory();

        nw.getCheckPoint().copyFrom(new NeedlePointer()); // reset checkpoint

        Date startDate = new Date();
        Date lapDate = new Date();
        System.out.println("Start test for " + TEST_COUNT + " pointers");
        long counter = 0;
        long lapCounter = 0;
        long offset = 0;
        BucketFNVHash hashFunc = new BucketFNVHash(1000000000L);
        while (counter < TEST_COUNT) {
            NeedlePointer needlePointer = new NeedlePointer();
            String key = "MYVERYNICEKEY" + counter;
            long bucket = hashFunc.hash(key);
            needlePointer.setNeedleFileNumber(4);
            needlePointer.setNeedleOffset(offset++);
            nw.writeNeedlePointer(bucket, needlePointer);
            counter++;
            Date lapDate2 = new Date();
            long spent = lapDate2.getTime() - lapDate.getTime();
            if (spent >= 1000 || (counter - lapCounter > TARGET_TPS)) { // Check each second or target tps
                if (spent < 1000) { // pause when tps reached
                    Thread.sleep(1000 - spent);
                    System.out.print(".");
                } else
                    System.out.print("*");
                lapDate = lapDate2; // Reset lap time
                lapCounter = counter; // Reset tps copunter
            }
        }
        long timeSpent = new Date().getTime() - startDate.getTime();
        System.out.println("\n\nWriting before cache commit of " + TEST_COUNT + " pointers \n"
                + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: "
                + (TEST_COUNT / timeSpent * 1000) + " tps");

        timeSpent = new Date().getTime() - startDate.getTime();
        System.out.println("\n\nProcessed writing of " + TEST_COUNT + " pointers \n" + "\tTotal time: "
                + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT / timeSpent * 1000) + " tps");
        System.out.println("Max cycle time = " + (nw.getMaxCycleTimePass1() + nw.getMaxCycleTimePass2()));

    } catch (Throwable th) {
        th.printStackTrace();
    }

}