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:mx.itdurango.rober.siitdocentes.ActivityAlumnos.java

/**
 * Permite generar un archivo .CSV con la estructura que se necesitara para poder manipular los datos en la PC
 * y subirlo de nuevo.//from   w  w  w . jav a2  s.  com
 */
private void descargaPlantilla() {
    //el nombre del archivo corresponde a la materia que se est viendo
    String filename = materia;
    FileOutputStream outputStream;
    //Se genera el archivo (vaco) en la ruta seleccionada previamente "m_chosenDir"
    File file = new File(m_chosenDir, filename + ".csv");
    String dato = "";
    try {
        //preparacin del archivo para poder escribir datos en el
        outputStream = new FileOutputStream(file);

        ArrayList<AlumnosParciales> listado_alumnos = gcs;
        //se crea el encabezado, como sigue:
        // NOCTRL, NOMBRE, UNIDAD1, UNIDAD2, UNIDAD3,..., UNIDADN
        dato = "NOCTRL,NOMBRE,";
        String comas = "";
        //generacion de los nombres de undidad en base a la cantidad de calificaciones del primer registro.
        for (int i = 1; i < gcs.get(0).getCalificaciones().size(); i++) {
            dato += "UNIDAD " + i;
            //la variable comas, permite crear la estructura completa para las calificaciones en la impresin de los alumnos
            comas += ",";
        }
        dato += "\n"; //indicador del trmino de rengln

        //recorrer el listado para extraer los datos correspondientes.
        for (AlumnosParciales alumno : listado_alumnos) {
            dato += alumno.getControl() + "," + alumno.getNombre() + "," + comas;
            dato += "\n";
        }

        //almacenar la informacin en el archivo
        outputStream.write(dato.getBytes());
        //cerrra el archivo
        outputStream.close();

        Toast.makeText(this, "Archivo guardado con el nombre: " + filename, Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(this, getString(R.string.error_descargaPlantilla), Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
    file = null;
    System.gc(); //llamar al garbage collector para liberar memoria
}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!//  w  w w.jav  a2 s .co m
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param ideIdint DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();
        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.storeDraftMessage(getId(), mime, user);
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:org.asqatasun.service.command.AuditCommandImpl.java

@Override
public void process() {
    audit = auditDataService.getAuditWithTest(audit.getId());
    if (!audit.getStatus().equals(AuditStatus.PROCESSING)) {
        LOGGER.warn(//from w ww  .j  a  v a  2  s . c  o  m
                new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR)
                        .append(AuditStatus.PROCESSING).append(WAS_REQUIRED_LOGGER_STR).toString());
        return;
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Processing " + audit.getSubject().getURL());
    }
    // debug tools
    Date beginProcessDate = null;
    Date endProcessDate = null;
    Date endPersistDate;
    Long persistenceDuration = (long) 0;

    Long i = (long) 0;
    Long webResourceId = audit.getSubject().getId();
    Long nbOfContent = contentDataService.getNumberOfSSPFromWebResource(audit.getSubject(), HttpStatus.SC_OK);

    Set<ProcessResult> processResultSet = new HashSet<>();

    while (i.compareTo(nbOfContent) < 0) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(new StringBuilder("Processing from ").append(i).append(TO_LOGGER_STR)
                    .append(i + processingTreatmentWindow).append("for ").append(audit.getSubject().getURL())
                    .toString());
            beginProcessDate = Calendar.getInstance().getTime();
        }
        Collection<Content> contentList = contentDataService
                .getSSPWithRelatedContentFromWebResource(webResourceId, i, processingTreatmentWindow, false);
        processResultSet.clear();
        processResultSet.addAll(processorService.process(contentList, audit.getTestList()));
        for (ProcessResult processResult : processResultSet) {
            processResult.setGrossResultAudit(audit);
        }

        if (LOGGER.isDebugEnabled()) {
            endProcessDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Processing of ").append(processingTreatmentWindow)
                    .append(" elements took ").append(endProcessDate.getTime() - beginProcessDate.getTime())
                    .append(MS_LOGGER_STR).append("for ").append(audit.getSubject().getURL()).toString());
        }
        if (LOGGER.isDebugEnabled()) {
            for (Content content : contentList) {
                LOGGER.debug("Persisting result for page " + content.getURI());
            }
        }
        processResultDataService.saveOrUpdate(processResultSet);
        if (LOGGER.isDebugEnabled()) {
            endPersistDate = Calendar.getInstance().getTime();
            LOGGER.debug(new StringBuilder("Persist processing of ").append(processingTreatmentWindow)
                    .append(" elements took ").append(endPersistDate.getTime() - endProcessDate.getTime())
                    .append(MS_LOGGER_STR).append("for ").append(audit.getSubject().getURL()).toString());
            persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime());
        }
        i = i + processingTreatmentWindow;
        System.gc();
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration)
                .append(" ms to write in Disk while processing").toString());
    }

    if (processResultDataService.getNumberOfGrossResultFromAudit(audit) > 0) {
        setStatusToAudit(AuditStatus.CONSOLIDATION);
    } else {
        LOGGER.error("Audit has no gross result");
        setStatusToAudit(AuditStatus.ERROR);
    }
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(audit.getSubject().getURL() + " has been processed");
    }
}

From source file:com.panet.imeta.job.entries.xslt.JobEntryXSLT.java

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//from   www.  java  2 s  .  c  o  m

    String realxmlfilename = getRealxmlfilename();
    String realxslfilename = getRealxslfilename();
    String realoutputfilename = getRealoutputfilename();

    FileObject xmlfile = null;
    FileObject xslfile = null;
    FileObject outputfile = null;

    try

    {

        if (xmlfilename != null && xslfilename != null && outputfilename != null) {
            xmlfile = KettleVFS.getFileObject(realxmlfilename);
            xslfile = KettleVFS.getFileObject(realxslfilename);
            outputfile = KettleVFS.getFileObject(realoutputfilename);

            if (xmlfile.exists() && xslfile.exists()) {
                if (outputfile.exists() && iffileexists == 2) {
                    //Output file exists
                    // User want to fail
                    log.logError(toString(), Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                            + realoutputfilename + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(false);
                    result.setNrErrors(1);
                }

                else if (outputfile.exists() && iffileexists == 1) {
                    // Do nothing
                    if (log.isDebug())
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileExists1.Label") + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                    result.setResult(true);
                } else {
                    if (outputfile.exists() && iffileexists == 0) {
                        // the output file exists and user want to create new one with unique name
                        //Format Date

                        // Try to clean filename (without wildcard)
                        String wildcard = realoutputfilename.substring(realoutputfilename.length() - 4,
                                realoutputfilename.length());
                        if (wildcard.substring(0, 1).equals(".")) {
                            // Find wildcard
                            realoutputfilename = realoutputfilename.substring(0,
                                    realoutputfilename.length() - 4) + "_"
                                    + StringUtil.getFormattedDateTimeNow(true) + wildcard;
                        } else {
                            // did not find wildcard
                            realoutputfilename = realoutputfilename + "_"
                                    + StringUtil.getFormattedDateTimeNow(true);
                        }
                        if (log.isDebug())
                            log.logDebug(toString(),
                                    Messages.getString("JobEntryXSLT.OuputFileExists1.Label")
                                            + realoutputfilename
                                            + Messages.getString("JobEntryXSLT.OuputFileExists2.Label"));
                        log.logDebug(toString(),
                                Messages.getString("JobEntryXSLT.OuputFileNameChange1.Label")
                                        + realoutputfilename
                                        + Messages.getString("JobEntryXSLT.OuputFileNameChange2.Label"));
                    }

                    // Create transformer factory
                    TransformerFactory factory = TransformerFactory.newInstance();

                    if (xsltfactory.equals(FACTORY_SAXON)) {
                        // Set the TransformerFactory to the SAXON implementation.
                        factory = new net.sf.saxon.TransformerFactoryImpl();
                    }

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerFactoryInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerFactory", factory.getClass().getName()));

                    // Use the factory to create a template containing the xsl file
                    Templates template = factory
                            .newTemplates(new StreamSource(KettleVFS.getInputStream(xslfile)));

                    // Use the template to create a transformer
                    Transformer xformer = template.newTransformer();

                    if (log.isDetailed())
                        log.logDetailed(Messages.getString("JobEntryXSL.Log.TransformerClassInfos"), Messages
                                .getString("JobEntryXSL.Log.TransformerClass", xformer.getClass().getName()));

                    // Prepare the input and output files
                    Source source = new StreamSource(KettleVFS.getInputStream(xmlfile));
                    StreamResult resultat = new StreamResult(KettleVFS.getOutputStream(outputfile, false));

                    // Apply the xsl file to the source file and write the result to the output file
                    xformer.transform(source, resultat);

                    if (isAddFileToResult()) {
                        // Add output filename to output files
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                KettleVFS.getFileObject(realoutputfilename), parentJob.getJobname(),
                                toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    // Everything is OK
                    result.setResult(true);
                }
            } else {

                if (!xmlfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxmlfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                if (!xslfile.exists()) {
                    log.logError(toString(), Messages.getString("JobEntryXSLT.FileDoesNotExist1.Label")
                            + realxslfilename + Messages.getString("JobEntryXSLT.FileDoesNotExist2.Label"));
                }
                result.setResult(false);
                result.setNrErrors(1);
            }

        } else {
            log.logError(toString(), Messages.getString("JobEntryXSLT.AllFilesNotNull.Label"));
            result.setResult(false);
            result.setNrErrors(1);
        }
    } catch (Exception e) {
        log.logError(toString(),
                Messages.getString("JobEntryXSLT.ErrorXLST.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML1.Label") + realxmlfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXML2.Label")
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL1.Label") + realxslfilename
                        + Messages.getString("JobEntryXSLT.ErrorXLSTXSL2.Label") + e.getMessage());
        result.setResult(false);
        result.setNrErrors(1);
    } finally {
        try {
            if (xmlfile != null)
                xmlfile.close();

            if (xslfile != null)
                xslfile.close();
            if (outputfile != null)
                outputfile.close();

            // file object is not properly garbaged collected and thus the file cannot
            // be deleted anymore. This is a known problem in the JVM.

            System.gc();
        } catch (IOException e) {
        }
    }

    return result;
}

From source file:com.panet.imeta.job.entries.copyfiles.JobEntryCopyFiles.java

private boolean ProcessFileFolder(String sourcefilefoldername, String destinationfilefoldername,
        String wildcard, Job parentJob, Result result) {

    LogWriter log = LogWriter.getInstance();
    boolean entrystatus = false;
    FileObject sourcefilefolder = null;
    FileObject destinationfilefolder = null;

    // Clear list files to remove after copy process
    // This list is also added to result files name
    list_files_remove.clear();/*from ww  w.ja v a2 s  .  c  om*/
    list_add_result.clear();

    // Get real source, destination file and wildcard
    String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername);
    String realDestinationFilefoldername = environmentSubstitute(destinationfilefoldername);
    String realWildcard = environmentSubstitute(wildcard);

    try {

        // Here gc() is explicitly called if e.g. createfile is used in the
        // same
        // job for the same file. The problem is that after creating the
        // file the
        // file object is not properly garbaged collected and thus the file
        // cannot
        // be deleted anymore. This is a known problem in the JVM.

        System.gc();

        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername);
        destinationfilefolder = KettleVFS.getFileObject(realDestinationFilefoldername);

        if (sourcefilefolder.exists()) {

            // Check if destination folder/parent folder exists !
            // If user wanted and if destination folder does not exist
            // PDI will create it
            if (CreateDestinationFolder(destinationfilefolder)) {

                // Basic Tests
                if (sourcefilefolder.getType().equals(FileType.FOLDER) && destination_is_a_file)// destinationfilefolder.getType().equals(FileType.FILE))
                {
                    // Source is a folder, destination is a file
                    // WARNING !!! CAN NOT COPY FOLDER TO FILE !!!

                    log.logError(Messages.getString("JobCopyFiles.Log.Forbidden"),
                            Messages.getString("JobCopyFiles.Log.CanNotCopyFolderToFile",
                                    realSourceFilefoldername, realDestinationFilefoldername));

                    NbrFail++;

                } else {

                    if (destinationfilefolder.getType().equals(FileType.FOLDER)
                            && sourcefilefolder.getType().equals(FileType.FILE)) {
                        // Source is a file, destination is a folder
                        // Copy the file to the destination folder

                        destinationfilefolder.copyFrom(sourcefilefolder.getParent(),
                                new TextOneFileSelector(sourcefilefolder.getParent().toString(),
                                        sourcefilefolder.getName().getBaseName(),
                                        destinationfilefolder.toString()));
                        if (log.isDetailed())
                            log.logDetailed(Messages.getString("JobCopyFiles.Log.FileCopiedInfos"),
                                    Messages.getString("JobCopyFiles.Log.FileCopied",
                                            sourcefilefolder.getName().toString(),
                                            destinationfilefolder.getName().toString()));

                    } else if (sourcefilefolder.getType().equals(FileType.FILE) && destination_is_a_file) {
                        // Source is a file, destination is a file

                        destinationfilefolder.copyFrom(sourcefilefolder,
                                new TextOneToOneFileSelector(destinationfilefolder));
                    } else {
                        // Both source and destination are folders
                        if (log.isDetailed()) {
                            log.logDetailed("", "  ");
                            log.logDetailed(toString(), Messages.getString("JobCopyFiles.Log.FetchFolder",
                                    sourcefilefolder.toString()));

                        }
                        destinationfilefolder.copyFrom(sourcefilefolder,
                                new TextFileSelector(sourcefilefolder.toString(),
                                        destinationfilefolder.toString(), realWildcard, parentJob));
                    }

                    // Remove Files if needed
                    if (remove_source_files && !list_files_remove.isEmpty()) {
                        for (Iterator<String> iter = list_files_remove.iterator(); iter.hasNext()
                                && !parentJob.isStopped();) {
                            String fileremoventry = (String) iter.next();
                            // Remove ONLY Files
                            if (KettleVFS.getFileObject(fileremoventry).getType() == FileType.FILE) {
                                boolean deletefile = KettleVFS.getFileObject(fileremoventry).delete();
                                log.logBasic("", " ------ ");
                                if (!deletefile) {
                                    log.logError("      " + Messages.getString("JobCopyFiles.Log.Error"),
                                            Messages.getString(
                                                    "JobCopyFiles.Error.Exception.CanRemoveFileFolder",
                                                    fileremoventry));
                                } else {
                                    if (log.isDetailed())
                                        log.logDetailed(
                                                "      " + Messages
                                                        .getString("JobCopyFiles.Log.FileFolderRemovedInfos"),
                                                Messages.getString("JobCopyFiles.Log.FileFolderRemoved",
                                                        fileremoventry));
                                }
                            }
                        }
                    }

                    // Add files to result files name
                    if (add_result_filesname && !list_add_result.isEmpty()) {
                        for (Iterator<String> iter = list_add_result.iterator(); iter.hasNext();) {
                            String fileaddentry = (String) iter.next();
                            // Add ONLY Files
                            if (KettleVFS.getFileObject(fileaddentry).getType() == FileType.FILE) {
                                ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                        KettleVFS.getFileObject(fileaddentry), parentJob.getJobname(),
                                        toString());
                                result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                                if (log.isDetailed()) {
                                    log.logDetailed("", " ------ ");
                                    log.logDetailed(
                                            "      " + Messages.getString("JobCopyFiles.Log.ResultFilesName"),
                                            Messages.getString("JobCopyFiles.Log.FileAddedToResultFilesName",
                                                    fileaddentry));
                                }
                            }
                        }
                    }
                }
                entrystatus = true;
            } else {
                // Destination Folder or Parent folder is missing
                log.logError(toString(), Messages.getString("JobCopyFiles.Error.DestinationFolderNotFound",
                        realDestinationFilefoldername));
            }
        } else {
            log.logError(toString(),
                    Messages.getString("JobCopyFiles.Error.SourceFileNotExists", realSourceFilefoldername));

        }
    } catch (IOException e) {
        log.logError("Error", Messages.getString("JobCopyFiles.Error.Exception.CopyProcess",
                realSourceFilefoldername.toString(), destinationfilefolder.toString(), e.getMessage()));
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();

            } catch (IOException ex) {
            }
            ;
        }
        if (destinationfilefolder != null) {
            try {
                destinationfilefolder.close();

            } catch (IOException ex) {
            }
            ;
        }
    }

    return entrystatus;
}

From source file:com.futurologeek.smartcrossing.crop.CropImageActivity.java

private void clearImageView() {
    imageView.clear();
    if (rotateBitmap != null) {
        rotateBitmap.recycle();
    }
    System.gc();
}

From source file:graphene.util.fs.FileUtils.java

private static void waitSome() {
        try {/*from   w ww.j av  a2 s.c  o m*/
            Thread.sleep(500);
        } catch (final InterruptedException ee) {
            Thread.interrupted();
        } // ok
        System.gc();
    }

From source file:com.limegroup.gnutella.RouterService.java

/**
 * Starts a manual GC thread.//from  w w  w.j a v a  2  s  .  co  m
 */
private void startManualGCThread() {
    Thread t = new ManagedThread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(5 * 60 * 1000);
                } catch (InterruptedException ignored) {
                }
                LOG.trace("Running GC");
                System.gc();
                LOG.trace("GC finished, running finalizers");
                System.runFinalization();
                LOG.trace("Finalizers finished.");
            }
        }
    }, "ManualGC");
    t.setDaemon(true);
    t.start();
    LOG.trace("Started manual GC thread.");
}

From source file:com.hipu.bdb.util.FileUtils.java

/**
 * Delete the file now -- but in the event of failure, keep trying
 * in the future. // ww w.  ja  v  a  2s .c  o m
 * 
 * VERY IMPORTANT: Do not use with any file whose name/path may be 
 * reused, because the lagged delete could then wind up deleting the
 * newer file. Essentially, only to be used with uniquely-named temp
 * files. 
 * 
 * Necessary because some platforms (looking at you, 
 * JVM-on-Windows) will have deletes fail because of things like 
 * file-mapped buffers remaining, and there's no explicit way to 
 * unmap a buffer. (See 6-year-old Sun-stumping Java bug
 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038 )
 * We just have to wait and retry. 
 * 
 * (Why not just File.deleteOnExit? There could be an arbitrary, 
 * unbounded number of files in such a situation, that are only 
 * deletable a few seconds or minutes after our first attempt.
 * Waiting for JVM exist could mean disk exhaustion. It's also
 * unclear if the native FS class implementations of deleteOnExit
 * use RAM per pending file.)
 * 
 * @param fileToDelete
 */
public static synchronized void deleteSoonerOrLater(File fileToDelete) {
    pendingDeletes.add(fileToDelete);
    // if things are getting out of hand, force gc/finalization
    if (pendingDeletes.size() > 50) {
        LOGGER.warning(">50 pending Files to delete; forcing gc/finalization");
        System.gc();
        System.runFinalization();
    }
    // try all pendingDeletes
    Iterator<File> iter = pendingDeletes.listIterator();
    while (iter.hasNext()) {
        File pending = iter.next();
        if (pending.delete()) {
            iter.remove();
        }
    }
    // if things are still out of hand, complain loudly
    if (pendingDeletes.size() > 50) {
        LOGGER.severe(">50 pending Files to delete even after gc/finalization");
    }
}