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.bellman.bible.android.control.page.CachedKeyPage.java

/**
 * make dictionary key lookup much faster
 *
 * @return/*from w ww . java2s  . c  o m*/
 */
public List<Key> getCachedGlobalKeyList() {
    if (getCurrentDocument() != null && mCachedGlobalKeyList == null) {
        try {
            Log.d(TAG, "Start to create cached key list for " + getCurrentDocument());
            // this cache is cleared in setCurrentDoc
            mCachedGlobalKeyList = new ArrayList<Key>();

            for (Key key : getCurrentDocument().getGlobalKeyList()) {
                // root key has no name and can be ignored but also check for any other keys with no name
                if (!StringUtils.isEmpty(key.getName())) {
                    mCachedGlobalKeyList.add(key);
                }
            }

        } catch (OutOfMemoryError oom) {
            mCachedGlobalKeyList = null;
            System.gc();
            Log.e(TAG, "out of memory", oom);
            throw oom;
        } catch (Exception e) {
            mCachedGlobalKeyList = null;
            System.gc();
            Log.e(TAG, "Error getting keys for " + getCurrentDocument(), e);
            Dialogs.getInstance().showErrorMsg(R.string.error_occurred, e);
        }
        Log.d(TAG, "Finished creating cached key list len:" + mCachedGlobalKeyList.size());
    }
    return mCachedGlobalKeyList;
}

From source file:com.liferay.portal.events.GarbageCollectorAction.java

public void run(HttpSession ses) throws ActionException {

    try {//from  w ww. jav  a 2  s  .  c o m
        Runtime runtime = Runtime.getRuntime();

        NumberFormat nf = NumberFormat.getInstance();

        _log.debug("Before GC: " + nf.format(runtime.freeMemory()) + " free, "
                + nf.format(runtime.totalMemory()) + " total, and " + nf.format(runtime.maxMemory()) + " max");

        _log.debug("Running garbage collector");

        System.gc();

        _log.debug("After GC: " + nf.format(runtime.freeMemory()) + " free, " + nf.format(runtime.totalMemory())
                + " total, and " + nf.format(runtime.maxMemory()) + " max");
    } catch (Exception e) {
        throw new ActionException(e);
    }
}

From source file:com.fizzed.rocker.ConstantPoolMain.java

public void run(String[] args) throws Exception {
    // do this call before anything is measured -- by doing it once it'll
    // trigger a load of ALL used classes underneath which eat up memory
    // and will effect measuring the effects of the two approaches
    //DynamicStringLoader.loadStringBytes("com.fizzed.rocker.ConstantPoolMain$Test", "TEST_TEXT1");
    PlainTextUnloadedClassLoader.load("com.fizzed.rocker.ConstantPoolMain$Test", "UTF-8").get("TEST_TEXT1");
    loadStringAsInputStream("pom.xml");
    System.gc();

    System.out.println("-----------------------------");
    System.out.println("After startup");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain$PlainText");
    garbageCollectAndPrintMemory();//from  w  w w.  ja va  2s  .  c  o m

    System.out.println("About to load Strings class. Press any key to continue...");
    System.in.read();

    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // COMMENT IN/OUT METHODS BELOW TO TRY THEM OUT
    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    // METHOD 1: via single use classloader, class it loads will be GC'ed
    //byte[] bytes = DynamicStringLoader.loadStringBytes("com.fizzed.rocker.ConstantPoolMain$Strings", "TEXT1");
    //byte[] bytes = PlainTextClassLoader.load("com.fizzed.rocker.ConstantPoolMain$PlainText", "UTF-8").get("TEXT1");
    //byte[] bytes = PlainTextClassLoader.load("com.fizzed.rocker.ConstantPoolMain$PlainText", "UTF-8").get("TEXT1");

    // METHOD 2: via static field access into bytes, then set to null
    //byte[] bytes = PlainText.TEXT1.getBytes(StandardCharsets.UTF_8);
    //Strings.TEXT1 = null;

    // METHOD 3: just for comparision, load class only
    //byte[] bytes = new byte[0];
    //Strings.doSomething();

    // METHOD 4: via normal resource file
    byte[] bytes = loadStringAsInputStream(
            "java6test/src/test/java/com/fizzed/rocker/ConstantPoolMain.strings");

    System.out.println("string byte length: " + bytes.length);

    System.out.println("-----------------------------");
    System.out.println("After load of Strings class");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain$PlainText");
    garbageCollectAndPrintMemory();

    bytes = null;
}

From source file:com.tbodt.trp.TheRapidPermuter.java

private static void doCommand(String command) {
    long before = System.nanoTime();

    // The most important line in the program!
    CommandProcessor.processCommand(command).ifPresent(data -> data.forEach(System.out::println));

    long after = System.nanoTime();
    if (cmd.hasOption('t'))
        System.out.println((after - before) / 1_000_000 + " ms");
    System.gc(); // why not?
}

From source file:com.fizzed.rocker.bin.ConstantPoolMain.java

public void run(String[] args) throws Exception {
    // do this call before anything is measured -- by doing it once it'll
    // trigger a load of ALL used classes underneath which eat up memory
    // and will effect measuring the effects of the two approaches
    //DynamicStringLoader.loadStringBytes("com.fizzed.rocker.ConstantPoolMain$Test", "TEST_TEXT1");
    PlainTextUnloadedClassLoader//from w  ww  . j a  v  a  2s  .c  o m
            .load(this.getClass().getClassLoader(), "com.fizzed.rocker.ConstantPoolMain$Test", "UTF-8")
            .get("TEST_TEXT1");
    loadStringAsInputStream("pom.xml");
    System.gc();

    System.out.println("-----------------------------");
    System.out.println("After startup");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain$PlainText");
    garbageCollectAndPrintMemory();

    System.out.println("About to load Strings class. Press any key to continue...");
    System.in.read();

    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    // COMMENT IN/OUT METHODS BELOW TO TRY THEM OUT
    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    // METHOD 1: via single use classloader, class it loads will be GC'ed
    //byte[] bytes = DynamicStringLoader.loadStringBytes("com.fizzed.rocker.ConstantPoolMain$Strings", "TEXT1");
    //byte[] bytes = PlainTextClassLoader.load("com.fizzed.rocker.ConstantPoolMain$PlainText", "UTF-8").get("TEXT1");
    //byte[] bytes = PlainTextClassLoader.load("com.fizzed.rocker.ConstantPoolMain$PlainText", "UTF-8").get("TEXT1");

    // METHOD 2: via static field access into bytes, then set to null
    //byte[] bytes = PlainText.TEXT1.getBytes(StandardCharsets.UTF_8);
    //Strings.TEXT1 = null;

    // METHOD 3: just for comparision, load class only
    //byte[] bytes = new byte[0];
    //Strings.doSomething();

    // METHOD 4: via normal resource file
    byte[] bytes = loadStringAsInputStream(
            "java6test/src/test/java/com/fizzed/rocker/ConstantPoolMain.strings");

    System.out.println("string byte length: " + bytes.length);

    System.out.println("-----------------------------");
    System.out.println("After load of Strings class");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain");
    isClassLoaded("com.fizzed.rocker.ConstantPoolMain$PlainText");
    garbageCollectAndPrintMemory();

    bytes = null;
}

From source file:icap.IcapServerDaemon.java

/**
 * Free all GS resources/* ww  w .  j  ava2 s .c  om*/
 * This method is called after stop() call to cleanup everything
 * @see org.apache.commons.daemon.Daemon#destroy()
 */
public void destroy() {
    //icap.IcapServer.stopServers();
    System.gc();
}

From source file:com.github.dozermapper.core.functional_tests.PerformanceTest.java

@After
public void tearDown() throws Exception {
    System.gc();
    Thread.sleep(100);
}

From source file:com.joey.software.memoryToolkit.MemoryUsagePanel.java

public static JFrame getMemoryUsagePanel(int dataNum, int delay) {
    final MemoryUsagePanel u = new MemoryUsagePanel(dataNum, delay);
    JFrame f = new JFrame("Memory Usage");
    f.setLayout(new BorderLayout());
    f.getContentPane().add(u, BorderLayout.CENTER);
    f.setSize(800, 400);/*from  ww  w . ja  va  2  s. com*/
    f.setVisible(true);

    final JButton runButton = new JButton("Start");
    runButton.addActionListener(new ActionListener() {

        boolean running = false;

        @Override
        public void actionPerformed(ActionEvent e) {
            if (running) {
                running = false;
                u.stopUpdating();
                runButton.setText("Start");
            } else {
                running = true;
                u.startUpdating();
                runButton.setText("Stop");
            }
        }
    });

    JButton garbage = new JButton("Run GC");
    garbage.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.gc();
        }
    });

    JPanel temp = new JPanel(new GridLayout(1, 1));

    temp.add(runButton);
    temp.add(garbage);

    f.getContentPane().add(temp, BorderLayout.SOUTH);

    return f;
}

From source file:com.login.android.cardapio.garcom.util.DrawableManager.java

public Drawable fetchDrawable(String urlString) {
    if (drawableMap.containsKey(urlString)) {
        return drawableMap.get(urlString);
    }//  ww  w .j a v a  2 s. c  o  m
    try {

        InputStream is = fetch(urlString);

        Drawable drawable = Drawable.createFromStream(is, "src");

        if (drawable != null) {
            drawableMap.put(urlString, drawable);
        } else {
            Log.w(this.getClass().getSimpleName(), "could not get thumbnail");
        }

        return drawable;
    } catch (MalformedURLException e) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    } catch (IOException e) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    } catch (OutOfMemoryError Err) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", Err);
        System.gc();
        return null;
    }
}

From source file:com.almende.eve.test.TestWake.java

/**
 * Test wake example./*ww  w.  j a va 2  s.co  m*/
 */
@Test
public void testWake() {

    final AgentConfig config = new AgentConfig("testWakeAgent");

    // First we need to setup the WakeService: (Either keep a global pointer
    // to the wake service, or obtain it again through the same
    // configuration)
    final InstantiationServiceConfig isConfig = new InstantiationServiceConfig();
    final FileStateConfig stateconfig = new FileStateConfig();
    stateconfig.setPath(".wakeservices");
    stateconfig.setId("testWakeService");
    isConfig.setState(stateconfig);

    config.setInstantiationService(isConfig);

    final HttpTransportConfig transConfig = new HttpTransportConfig();
    transConfig.setServletUrl("http://localhost:8080/agents/");
    transConfig.setServletLauncher("JettyLauncher");
    transConfig.setServletClass(DebugServlet.class.getName());
    final ObjectNode jettyParms = JOM.createObjectNode();
    jettyParms.put("port", 8080);
    transConfig.set("jetty", jettyParms);
    config.addTransport(transConfig);

    // Now create a WakeAble Agent
    WeakReference<Agent> test = new WeakReference<Agent>(new MyAgent(config));

    // after a while the agent is unloaded:
    System.gc();
    System.gc();
    try {
        Thread.sleep(1000);
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }
    System.gc();
    System.gc();

    // By now the agent should be unloaded:
    assertNull(test.get());

    // Now some other agent calls the agent:
    new Agent("other", null) {
        public void test() {
            try {
                call(URI.create("local:testWakeAgent"), "helloWorld", null, new AsyncCallback<String>() {

                    @Override
                    public void onSuccess(String result) {
                        called.value = true;
                    }

                    @Override
                    public void onFailure(Exception exception) {
                        fail();
                    }

                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.test();

    // Give the async call time to reach the agent (and wake the agent in
    // the proces);
    try {
        Thread.sleep(1000);
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }
    assertTrue(called.value);
}