Example usage for java.lang Runtime totalMemory

List of usage examples for java.lang Runtime totalMemory

Introduction

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

Prototype

public native long totalMemory();

Source Link

Document

Returns the total amount of memory in the Java virtual machine.

Usage

From source file:Main.java

public static void main(String[] args) {

    // print the total memory
    Runtime runTime = Runtime.getRuntime();

    System.out.println(runTime.totalMemory());

}

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   w w w.  j a  va  2 s.  com

    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();//from  www.ja v a  2  s .  c o 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();/*  w ww.  j  a va  2 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 < 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  av a2 s  .  c o  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.pircbotx.Benchmark.java

public static void main(String[] args) throws Exception {
    //Change logging to no-op
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    JoranConfigurator configurator = new JoranConfigurator();
    configurator.setContext(context);/* w  w w . j  av  a2 s  . c o m*/
    context.reset();
    configurator.doConfigure(Benchmark.class.getResource("/logback-nop.xml"));
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);

    if (args.length != 1) {
        System.err.println("Must specify thread count:");
        System.err.println(" -1: GenericListenerManager");
        System.err.println(" 0: ThreadedListenerManager (default threads)");
        System.err.println(" 1+: ThreadedListenerManager (specified threads)");
        return;
    }
    int threadCount = Integer.parseInt(args[0]);

    //Init
    String[][] responseTemplateGroups = new String[13][];
    responseTemplateGroups[0] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter PRIVMSG ${channel} ?jmeter ${thisNick}" };
    responseTemplateGroups[1] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter PRIVMSG ${targetNick} ?jmeter ${thisNick}" };
    responseTemplateGroups[2] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter PRIVMSG ${channel} :${thisNick}" };
    responseTemplateGroups[3] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter PRIVMSG ${channel} :\u0001ACTION ${thisNick}\u0001" };
    responseTemplateGroups[4] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter NOTICE ${channel} :${thisNick}" };
    responseTemplateGroups[5] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter PRIVMSG ${targetNick} :${thisNick}" };
    responseTemplateGroups[6] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter PRIVMSG ${targetNick} :\u0001ACTION ${thisNick}\u0001" };
    responseTemplateGroups[7] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter MODE ${channel} +o ${thisNick}",
            ":${thisNick}!~jmeter@bots.jmeter MODE ${channel} -o ${thisNick}" };
    responseTemplateGroups[8] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter MODE ${channel} +v ${thisNick}",
            ":${thisNick}!~jmeter@bots.jmeter MODE ${channel} -v ${thisNick}" };
    responseTemplateGroups[9] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter KICK ${channel} ${targetNick}: ${thisNick}",
            ":${thisNick}!~jmeter@bots.jmeter JOIN :${channel}" };
    responseTemplateGroups[10] = new String[] {
            ":${thisNick}!~jmeter@bots.jmeter MODE ${channel} +b ${thisNick}!*@*",
            ":${thisNick}!~jmeter@bots.jmeter MODE ${channel} -b ${thisNick}!*@*" };
    responseTemplateGroups[11] = new String[] { ":${thisNick}!~jmeter@bots.jmeter PART ${channel}",
            ":${thisNick}!~jmeter@bots.jmeter JOIN :${channel}" };
    responseTemplateGroups[12] = new String[] { ":${thisNick}!~jmeter@bots.jmeter QUIT :${thisNick}",
            ":${thisNick}!~jmeter@bots.jmeter JOIN :${channel}" };

    Runtime runtime = Runtime.getRuntime();
    System.out.println("Memory usage: " + (runtime.totalMemory() / 1024));

    System.out.println("Building responses");
    responseGroups = new String[MAX_USERS * MAX_CHANNELS * MAX_ITERATIONS * responseTemplateGroups.length][];
    int responseGroupsCounter = 0;
    SecureRandom sortRandom = new SecureRandom();
    String[] searchList = new String[] { "${thisNick}", "${channel}" };
    for (int userNum = 0; userNum < MAX_USERS; userNum++) {
        shuffleArray(responseTemplateGroups, sortRandom);
        for (int channelNum = 0; channelNum < MAX_CHANNELS; channelNum++) {
            String[] replaceList = new String[] { "umark" + userNum, "#cbench" + channelNum };
            for (int iterationNum = 0; iterationNum < MAX_ITERATIONS; iterationNum++)
                //Parse template
                for (int templateNum = 0, templateSize = responseTemplateGroups.length; templateNum < templateSize; templateNum++) {
                    String[] templateGroup = responseTemplateGroups[templateNum];
                    String[] responseGroup = new String[templateGroup.length];
                    int responseCounter = 0;
                    for (int templateLineNum = 0, templateLineSize = templateGroup.length; templateLineNum < templateLineSize; templateLineNum++)
                        responseGroup[responseCounter++] = StringUtils
                                .replaceEachRepeatedly(templateGroup[templateLineNum], searchList, replaceList);
                    responseGroups[responseGroupsCounter++] = responseGroup;
                }
        }
    }

    System.out.println("Sorting");
    shuffleArray(responseGroups, sortRandom);

    //Init other objects
    StopWatch stopWatch = new StopWatch();
    ListenerManager listenerManager;
    if (threadCount == -1)
        listenerManager = new GenericListenerManager();
    else if (threadCount == 0)
        listenerManager = new ThreadedListenerManager(Executors.newCachedThreadPool());
    else
        listenerManager = new ThreadedListenerManager(Executors.newFixedThreadPool(threadCount));
    PircBotX bot = new PircBotX(TestUtils.generateConfigurationBuilder().setListenerManager(listenerManager)
            .addListener(new PircBotXJMeter()).buildConfiguration()) {
        @Override
        public boolean isConnected() {
            return true;
        }

        @Override
        protected void sendRawLineToServer(String line) {
            //Do nothing
        }
    };
    inputParser = bot.getInputParser();

    System.out.println("Waiting 5 seconds");
    Thread.sleep(5000);

    System.out.println("Executing with " + responseGroups.length + " response groups");
    int counter = run(stopWatch);

    System.out.println("Parsed " + counter + " enteries in " + stopWatch.toString());
    System.out.println(
            "Average parse speed: " + ((float) counter / (stopWatch.getTime() / 1000)) + " per second");

    System.out.println("Memory usage: " + (runtime.totalMemory() / 1024));

    //Kill the listener manager so the JVM can shutdown
    if (listenerManager instanceof ThreadedListenerManager)
        ((ThreadedListenerManager) listenerManager).shutdown();
}

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  a2s.co  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:eu.delving.sip.Application.java

public static void main(final String[] args) throws StorageException {
    storageFinder.setArgs(args);/*ww  w . ja  v  a 2s . c  o m*/
    Runtime rt = Runtime.getRuntime();
    int totalMemory = (int) (rt.totalMemory() / 1024 / 1024);
    System.out.println("Total memory: " + totalMemory);
    if (totalMemory < 900) {
        memoryNotConfigured();
    } else {
        EventQueue.invokeLater(LAUNCH);
    }
}

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  .  jav  a  2 s.com*/
    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();
    }
}