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:eu.stratosphere.test.util.AbstractTestBase.java

@After
public void stopCluster() throws Exception {
    try {//from   w  w  w.  ja  v  a 2 s.  co  m
        if (this.executor != null) {
            this.executor.stop();
            this.executor = null;
            FileSystem.closeAll();
            System.gc();
        }
    } finally {
        deleteAllTempFiles();
    }
}

From source file:com.netspective.commons.xdm.XdmComponentFactory.java

public static XdmComponent getCachedComponent(String systemId, int flags) {
    XdmComponent component = (XdmComponent) componentsBySystemId.get(systemId);
    if (component != null) {
        // If we have a component and we don't want to allow re-loads then we use what we have
        if ((flags & XDMCOMPFLAG_ALLOWRELOAD) == 0)
            return component;

        // If we have a component and we do allow reloads but the source has not changed, then use what we have
        if (!component.getInputSource().sourceChanged())
            return component;

        // If we get to this point, we have an existing component and we are allowing reloads but the source seems
        // to have changed; we need to read the entire component again so remove the instance from the map and set
        // it to null to give the GC a hint to get rid of the instance as soon as possible.
        component.removedFromCache(componentsBySystemId, systemId, flags);
        componentsBySystemId.remove(systemId);
        component = null;/*  w  ww .  j a  v a  2s  .c  om*/

        // call the garbage-collector at the earliest convenience because all the old components should now be freed
        System.gc();
    }
    return component;
}

From source file:br.com.hslife.orcamento.controller.ArquivoController.java

public String find() {
    initializeEntity();/*w ww  .j  a  v  a 2  s. c  o m*/

    // Invoca o Garbage Collector
    System.gc();

    try {
        criterio.setUsuario(getUsuarioLogado());
        listEntity = getService().buscarPorCriterioArquivo(criterio);

        // Varivel que contabiliza quantos arquivos podem ser descartados
        int quantDescartar = 0;
        BigDecimal bytesALiberar = new BigDecimal(0);

        // Calcula o espao ocupado e injeta as opes do sistema nas entidades
        espacoOcupado = new BigDecimal(0);
        Map<String, Integer> opcoesSistema = getOpcoesSistema().getOpcoesArquivosAnexados(getUsuarioLogado());
        for (Arquivo a : listEntity) {
            espacoOcupado = espacoOcupado.add(new BigDecimal(a.getTamanho()));
            a.setOpcoesSistema(opcoesSistema);
            if (a.isPrazoExpirado()) {
                quantDescartar++;
                bytesALiberar = bytesALiberar.add(new BigDecimal(a.getTamanho()));
            }
        }

        // Retorna uma mensagem informando quandos arquivos podem ser excludos
        if (quantDescartar != 0) {
            warnMessage(quantDescartar + " arquivo(s) pode(m) ser descartado(s), liberando "
                    + new DecimalFormat("#,##0.##").format(bytesALiberar) + " bytes no disco.");
        }
    } catch (ValidationException | BusinessException be) {
        errorMessage(be.getMessage());
    }

    return "";
}

From source file:com.foregroundgalleryplugin.ForegroundGalleryLauncher.java

/**
 * Called when the camera view exits./* w ww  .  j a  v  a  2 s  .  co  m*/
 * 
 * @param requestCode
 *            The request code originally supplied to
 *            startActivityForResult(), allowing you to identify who this
 *            result came from.
 * @param resultCode
 *            The integer result code returned by the child activity through
 *            its setResult().
 * @param intent
 *            An Intent, which can return result data to the caller (various
 *            data can be attached to Intent "extras").
 */
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (resultCode == Activity.RESULT_OK) {

        Uri uri = intent.getData();
        ContentResolver resolver = this.cordova.getActivity().getContentResolver();

        try {
            Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            bitmap = scaleBitmap(bitmap);
            this.processPicture(bitmap);
            bitmap.recycle();
            bitmap = null;
            System.gc();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            this.failPicture("Error retrieving image.");
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Selection cancelled.");
    } else {
        this.failPicture("Selection did not complete!");
    }
}

From source file:com.imagelake.android.packages.Servlet_Packages.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {//w  ww . j a  v a  2s  . c o  m
        String type = request.getParameter("type");
        if (type != null) {
            if (type.equals("Load_all")) {
                JSONObject jo = new JSONObject();

                FreeTrial ft1 = fdi.getAFreeTrail(1);

                jo.put("ft_id", ft1.getFreeId());
                jo.put("ft_days", ft1.getDays());
                jo.put("ft_dwn", ft1.getDownload_count());

                FreeTrial ft2 = fdi.getAFreeTrail(2);

                jo.put("ft2_id", ft2.getFreeId());
                jo.put("ft2_days", ft2.getDays());
                jo.put("ft2_dwn", ft2.getDownload_count());

                out.write("json=" + jo.toJSONString());
                System.out.println(jo.toJSONString());
            } else if (type.equals("free_trial")) {

                String uid = request.getParameter("uid");

                List<UserHasPackage> uhpList = null;
                UserHasPackage uhp = null;
                List<FreeTrial> fr = null;
                FreeTrial ft = null;

                User u = udi.getUser(Integer.parseInt(uid));
                if (u == null) {
                    //checkig user has signIn
                    out.write("msg=Internal server error.");
                } else {

                    if (u.getUser_type() == 2 || u.getUser_type() == 3) {
                        uhpList = new UserHasPackageDAOImp().getUserPackages(u.getUser_id());
                        fr = new FreeTrialDAOImp().getFreeTrail();

                        for (FreeTrial freeTrial : fr) {
                            System.gc();
                            if (freeTrial.getPackage_type_id() == 1) {
                                ft = freeTrial;
                                break;
                            }
                        }

                        //get all list of all the packages user have and had
                        if (uhpList.isEmpty()) {
                            //if that list is not empty
                            calReturn.add(Calendar.DATE, ft.getDays());
                            uhp = new UserHasPackage();
                            uhp.setCredit_count(0);
                            uhp.setDownload_count(ft.getDownload_count());
                            uhp.setExpire_date(dateFormat.format(calReturn.getTime()));
                            uhp.setPackage_id(ft.getFreeId());
                            uhp.setPackage_type(1);
                            uhp.setPurchase_date(dateFormat.format(cal.getTime()));
                            uhp.setState(1);
                            uhp.setUser_id(u.getUser_id());
                            uhp.setLast_date(dateFormat.format(cal.getTime()));
                            uhp.setDuration(ft.getDays());
                            System.gc();
                            boolean ok = new UserHasPackageDAOImp().addAPackage(uhp);
                            out.write("msg=Free trial package is successfully activated");
                        } else {
                            //if the user have some packages
                            boolean seven = false;
                            for (UserHasPackage userHasPackage : uhpList) {
                                System.gc();
                                //check whether he have perchase 7 day free pack before
                                if (userHasPackage.getPackage_type() == 1
                                        && userHasPackage.getUser_id() == u.getUser_id()) {
                                    seven = true;
                                    break;
                                } else if (userHasPackage.getPackage_type() == 2
                                        && userHasPackage.getUser_id() == u.getUser_id()) {
                                    seven = true;
                                    break;
                                }

                            }
                            //if user have alrady had a free trial
                            if (seven) {
                                out.write("msg=Free trial packages are available to new users only");
                            } else {
                                calReturn.add(Calendar.DATE, ft.getDays());
                                uhp = new UserHasPackage();
                                uhp.setCredit_count(0);
                                uhp.setDownload_count(ft.getDownload_count());
                                uhp.setExpire_date(dateFormat.format(calReturn.getTime()));
                                uhp.setPackage_id(ft.getFreeId());
                                uhp.setPackage_type(1);
                                uhp.setPurchase_date(dateFormat.format(cal.getTime()));
                                uhp.setState(1);
                                uhp.setUser_id(u.getUser_id());
                                uhp.setLast_date(dateFormat.format(cal.getTime()));
                                uhp.setDuration(ft.getDays());
                                System.gc();
                                boolean ok = new UserHasPackageDAOImp().addAPackage(uhp);
                                out.write("msg=Free trial package is successfully activated");
                            }
                        }

                    } else {
                        out.write("msg=Packages are available to buyers & contributors only.");
                    }
                }
            } else if (type.equals("Ultimate_free_trial")) {

                String uid = request.getParameter("uid");

                List<UserHasPackage> uhpList = null;
                UserHasPackage uhp = null;
                List<FreeTrial> fr = null;
                FreeTrial ft = null;

                User u = udi.getUser(Integer.parseInt(uid));
                if (u == null) {
                    //checkig user has signIn
                    out.write("msg=Internal server error.");
                } else {
                    if (u.getUser_type() == 2 || u.getUser_type() == 3) {
                        uhpList = new UserHasPackageDAOImp().getUserPackages(u.getUser_id());
                        fr = new FreeTrialDAOImp().getFreeTrail();

                        for (FreeTrial freeTrial : fr) {
                            System.gc();
                            if (freeTrial.getPackage_type_id() == 2) {
                                ft = freeTrial;
                                break;
                            }
                        }
                        //get all list of all the packages user have and had
                        if (uhpList.isEmpty()) {
                            //if that list is not empty
                            calReturn.add(Calendar.DATE, ft.getDays());
                            uhp = new UserHasPackage();
                            uhp.setCredit_count(0);
                            uhp.setDownload_count(ft.getDownload_count());
                            uhp.setExpire_date(dateFormat.format(calReturn.getTime()));
                            uhp.setPackage_id(ft.getFreeId());
                            uhp.setPackage_type(2);
                            uhp.setPurchase_date(dateFormat.format(cal.getTime()));
                            uhp.setState(1);
                            uhp.setUser_id(u.getUser_id());
                            uhp.setLast_date(dateFormat.format(cal.getTime()));
                            uhp.setDuration(ft.getDays());

                            System.gc();
                            boolean ok = new UserHasPackageDAOImp().addAPackage(uhp);
                            out.write("msg=Unlimited Free trial package is successfully activated");
                        } else {
                            //if the user have some packages
                            boolean seven = false;
                            for (UserHasPackage userHasPackage : uhpList) {
                                System.gc();
                                //check whether he have perchase 7 day free pack before
                                if (userHasPackage.getPackage_type() == 1
                                        && userHasPackage.getUser_id() == u.getUser_id()) {
                                    seven = true;
                                    break;
                                } else if (userHasPackage.getPackage_type() == 2
                                        && userHasPackage.getUser_id() == u.getUser_id()) {
                                    seven = true;
                                    break;
                                }

                            }
                            //if user have alrady had a free trial
                            if (seven) {
                                out.write("msg=Unlimited Free trial packages are available to new users only");
                            } else {
                                calReturn.add(Calendar.DATE, ft.getDays());
                                uhp = new UserHasPackage();
                                uhp.setCredit_count(0);
                                System.out.println("ft get count" + ft.getDownload_count());
                                uhp.setDownload_count(ft.getDownload_count());
                                uhp.setExpire_date(dateFormat.format(calReturn.getTime()));
                                uhp.setPackage_id(ft.getFreeId());
                                uhp.setPackage_type(2);
                                uhp.setPurchase_date(dateFormat.format(cal.getTime()));
                                uhp.setState(1);
                                uhp.setUser_id(u.getUser_id());
                                uhp.setLast_date(dateFormat.format(cal.getTime()));
                                uhp.setDuration(ft.getDays());

                                System.gc();
                                boolean ok = new UserHasPackageDAOImp().addAPackage(uhp);
                                out.write("msg=Unlimited Free trial package is successfully activated");
                            }
                        }

                    } else {
                        out.write("msg=Packages are available to buyers & contributors only.");
                    }
                }
            } else if (type.equals("load_sub")) {
                System.out.println(type);
                List<DownloadCount> li = dcdi.listAll();
                ja = new JSONArray();
                if (!li.isEmpty()) {

                    for (DownloadCount dw : li) {

                        List<SubscriptionPackage> list = sdi.listByDownCount(dw.getId());
                        DownloadCount d = dcdi.getCount(dw.getId());

                        for (SubscriptionPackage s : list) {
                            if (s.getState() != 3 && s.getSubscription_type_id() == 1) {
                                JSONObject jo = new JSONObject();
                                jo.put("id", s.getSubscription_id());
                                jo.put("du", s.getDuration());
                                jo.put("dwn", dw.getCount());
                                jo.put("pimg", s.getPer_image());
                                jo.put("prc",
                                        df.format(s.getPer_image() * 30 * s.getDuration() * d.getCount()));
                                jo.put("disc", s.getDiscount());
                                jo.put("state", s.getState());
                                ja.add(jo);
                            }
                        }

                    }
                }
                out.write("json=" + ja.toJSONString());
                System.out.println(ja.toJSONString());
            } else if (type.equals("load_crd")) {
                List<CreditsPackage> creList = cdi.listAll();
                ja = new JSONArray();
                for (CreditsPackage c : creList) {
                    if (c.getState() != 3) {
                        JSONObject jo = new JSONObject();
                        jo.put("id", c.getCreditpack_id());
                        jo.put("du", c.getDuration());
                        jo.put("dwn", c.getCredits());
                        jo.put("pimg", c.getPer_image());
                        jo.put("prc", df.format(c.getPer_image() * c.getCredits()));
                        jo.put("disc", c.getDiscount());
                        jo.put("state", c.getState());
                        ja.add(jo);
                    }
                }

                out.write("json=" + ja.toJSONString());
                System.out.println(ja.toJSONString());
            }
        } else {
            out.write("msg=Internal server error,Please try again later.");
        }
    } catch (Exception e) {
        e.printStackTrace();
        out.write("msg=Internal server error,Please try again later.");
    }

}

From source file:com.example.pierre.applicompanies.library_http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*from w  ww  . j a  v a 2s.  c  om*/
 * @return response entity body or null
 * @throws java.io.IOException if reading entity or creating byte array failed
 */
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {

    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        buffer.append(tmp, 0, l);
                        sendProgressDataMessage(copyOfRange(tmp, 0, l));
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:cn.com.loopj.android.http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*from  w w  w . j a  v  a 2 s. com*/
 * @return response entity body or null
 * @throws IOException if reading entity or creating byte array failed
 */
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {

    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        buffer.append(tmp, 0, l);
                        sendProgressDataMessage(copyOfRange(tmp, 0, l));
                        sendProgressMessage(count, contentLength);
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:org.chromium.android_webview.test.AwContentsTest.java

@LargeTest
@Feature({ "AndroidWebView" })
public void testCreateAndGcManyTimes() throws Throwable {
    final int CONCURRENT_INSTANCES = 4;
    final int REPETITIONS = 16;
    // The system retains a strong ref to the last focused view (in InputMethodManager)
    // so allow for 1 'leaked' instance.
    final int MAX_IDLE_INSTANCES = 1;

    System.gc();

    pollOnUiThread(new Callable<Boolean>() {
        @Override/*www.ja  v a2s .c  om*/
        public Boolean call() {
            return AwContents.getNativeInstanceCount() <= MAX_IDLE_INSTANCES;
        }
    });
    for (int i = 0; i < REPETITIONS; ++i) {
        for (int j = 0; j < CONCURRENT_INSTANCES; ++j) {
            AwTestContainerView view = createAwTestContainerViewOnMainSync(mContentsClient);
            loadUrlAsync(view.getAwContents(), "about:blank");
        }
        assertTrue(AwContents.getNativeInstanceCount() >= CONCURRENT_INSTANCES);
        assertTrue(AwContents.getNativeInstanceCount() <= (i + 1) * CONCURRENT_INSTANCES);
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getActivity().removeAllViews();
            }
        });
    }

    System.gc();

    pollOnUiThread(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            return AwContents.getNativeInstanceCount() <= MAX_IDLE_INSTANCES;
        }
    });
}

From source file:com.enioka.jqm.tools.BasicTest.java

@After
public void after() {
    jqmlogger.debug("********* TEST CLEANUP");
    engine1.stop();/*  ww  w  .  j  a  va2  s.  c  o  m*/
    em.close();
    JqmClientFactory.resetClient();

    System.runFinalization();
    System.gc();
    System.runFinalization();
    System.gc();
    System.gc();
}

From source file:mx.unam.ecologia.gye.coalescence.app.MicrosatelliteExperiment.java

public final void run() {
    log.info("Running Simulations.");
    //Tree height samples
    m_Heights = new DoubleArrayList(m_NumMCSamples);
    //Total branch length samples
    m_TBLs = new DoubleArrayList(m_NumMCSamples);
    //Number of Mutations
    m_Mutations = new DoubleArrayList(m_NumMCSamples);

    long start = System.currentTimeMillis();
    for (int i = 0; i < m_NumMCSamples; i++) {
        IdentityGenerator.reset();//from  www.j  a  va2s  .  c  om
        m_Visitor.reset();

        //Generate coalescent genealogy
        m_Genealogy.generate();

        //Apply mutations traversing the tree
        UniParentalGene mrca = m_Genealogy.getMRCA();
        mrca.setCompoundSequence(m_MRCACompoundSequence.getCopy());
        UniParentalGene.traverse(mrca, m_Visitor);

        //analyze and store samples
        m_Analysis.addSample(m_Genealogy.getLeaves());
        m_Heights.add(m_Genealogy.getHeight());
        m_TBLs.add(m_Genealogy.getTotalBranchLength());
        m_Mutations.add(m_Visitor.getNumberOfMutations());

        //dispatch a mem clean up
        System.gc();
        //track progress
        if (i > 0 && i % 100 == 0) {
            System.out.print('#');
        }
    }
    long end = System.currentTimeMillis();
    m_SimTime = end - start;

    log.info("Finished Simulations in " + (m_SimTime / 1000) + " seconds.");
    double[] hs = StatsUtility.getStats(m_Heights);
    log.info("Genealogy Expected Height     = " + m_Genealogy.getExpectedHeight());
    log.info("Genealogy Expected Height Var = 1.159");
    log.info("Genealogy Height Mean     = " + hs[0]);
    log.info("Genealogy Height Variance = " + hs[1]);
    hs = StatsUtility.getStats(m_TBLs);
    log.info("Genealogy Expected TBL     = " + m_Genealogy.getExpectedTotalBranchLength());
    log.info("Genealogy Expected TBL Var = 6.579");
    log.info("Genealogy TBL Mean = " + hs[0]);
    log.info("Genealogy TBL Variance = " + hs[1]);
    hs = StatsUtility.getStats(m_Mutations);
    log.info("Number of Mutations Mean = " + hs[0]);
    log.info("Number of Mutations Var  = " + hs[1]);
    //log.info("Run Haplotypes");
    //PrintWriter pw = new PrintWriter(System.out);
    // HaplotypeFreqSet multilocus = m_Analysis.getRunHaplotypes(true);
    // HaplotypeFreqSet locus = m_Analysis.getRunHaplotypes(false);
    /*
        pw.println();
        pw.println();
        pw.println("MULTILOCUS");
        pw.println(multilocus.sort().toLengthResumeString());
            
        pw.println();
        pw.println();
        pw.println("LOCUS");
        pw.println(locus.sort().toLengthResumeString());
        */
    //pw.flush();
}